Dan Ackroyd wrote:
> This looks to solve a problem very similar to the one solved by the
> 'Memoize' annotation in HHVM -
> https://docs.hhvm.com/hack/attributes/special#__memoize
> However the memoize functionality seems a lot clearer to me, as it's
> less 'magic'; it doesn't make accessing a variable actually call a
> function.
On really it seems a very good feature focused on method call.
Maybe it can be done in same idea, by freezing the first result of method.
But I think hard do that with args.
Maybe something like that: http://pastebin.com/YKjEYeYF
Note: I know that is better an IoC, understand just as example.
Dan Ackroyd wrote:
> This code has a circular dependency:
>
> class Foo {
> public $a, $b;
> public __construct() {
> $this->a = lazy { return 1 + $this->b; }
> $this->b = lazy { return 1 + $this->a; }
> }
> }
>
> $foo = new Foo;
> echo $foo->a;
>
> $foo->a can't be resolved until $foo->b is resolved, and $foo->b can't
> be resolved until $foo->a is resolved.
Now back to topic, this circular dependency too occur with functions.
Basically if it happen, should throw a infinite recursion error.
(Currently I guess that PHP don't do that, but xdebug does)
In all case, $a should not depends of $b, when $b depends $a.
In this case, should have a bootstrap system, that turn it independent.
Example:
class Foo {
public $a, $b;
public __construct () {
$c = lazy { return generalDependency(); }
$this->a = lazy use ($c) { return 1 + $c; };
$this->b = lazy use ($c) { return 1 + $c; };
}
}
Dan Ackroyd wrote:
> Because the 'memoization' of functions is less magic, it is much less
> prone to this circular dependency problem.
I guess that memoization is another topic, but still very interesting,
as cited above.
So maybe it can be discussed apart of this email, if is reasonable.
Stanislav Malyshev wrote:
> > This Feature Request is about the implementation of lazy statements.
> >
> > Basically it should implements a 'lazy' keyword (or similar) and
> > structured like an anonymous function, except that it doesn't accepts
> > arguments, but accept the use() feature.
> >
> > $var = lazy { return 1; }
>
> Is this just keystroke saving for function() or is this supposed to do
> something additional?
It's similar to function (), but should be applied to variables or
properties only.
But exists an important difference between you use lazy vs function ().
$var1 = function () { sleep(5); return 1; }
$var2 = lazy { sleep(5); return 1; }
- $var1 should be called like $var1();
- If I call $var1() five times, it'll execute this structure over 25 seconds;
- If I try to write over $var1(), possible I should get an error
trying to write over int (1);
- $var2 should be called like $var2 directly;
- If I call $var2 five times, it'll execute once the structure,
custing 5 seconds only;
- If I try to write over $var2 it'll, in fact, write over $var2
processed structure, that stores int (1);