Skip to content

System.ILazy interface

Marcel Kloubert edited this page Oct 5, 2015 · 3 revisions

System.ILazy interface

Describes an object that provides a value that is created once at that the time it is being accessed.

Syntax

interface ILazy;

Methods

Name Description
[[isValueCreated() ILazy.isValueCreated() method]]
[[value() ILazy.value() method]]

Examples

Lazy class

Lambda expression

use \System\Lazy;

$obj = new Lazy('() => new \DateTime()');

// (false)
$ivc1 = $obj->isValueCreated();

// DateTime object
$value1 = $obj->value();

// (true)
$ivc2 = $obj->isValueCreated();

sleep(5);

$value2 = $obj->value();

// all are (true), because the value is created only one
$areSame1 = $value1 === $value2;
$areSame2 = $value1->getTimestamp() == $value2->getTimestamp();

Closure

use \System\Lazy;

$obj = new Lazy(function() {
                    return new \DateTime();
                });

// (false)
$ivc1 = $obj->isValueCreated();

// DateTime object
$value1 = $obj->value();

// (true)
$ivc2 = $obj->isValueCreated();

sleep(5);

$value2 = $obj->value();

// all are (true), because the value is created only once
$areSame1 = $value1 === $value2;
$areSame2 = $value1->getTimestamp() == $value2->getTimestamp();
Clone this wiki locally