On Thu, Jul 21, 2016, at 10:51 AM, David Rodrigues 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; }
>     $var = lazy use ($x) { return $x; }
> 
> It differ from anonymous function because this assignment is treated
> as variable, without need to call or check if it is a valid Closure
> all the time.
> 
> ---
> 
> Execution example:
> 
>     echo $var;
>     echo $var;
> 
> In this example, the first echo will execute the lazy statement and
> set the returned value directly to $var container, then will echo 1.
> The second echo will not execute the lazy anymore, because it was
> processed on first echo, so will just echo 1.
> 
> ---
> 
> It should be very useful on framework or package development because
> you can defines lazy properties that need to be calculated only when
> it is requested the first time.
> Should be useful too when you have a global variable like $user that
> you should not use all the time (in all requests).
> 
>     View::share('user', lazy { return User::find(session('user.id')); });
> 
> This code will be executed only on try read or write on $user variable.
> 
> ---
> 
> It should works from read or write, to the next code is valid:
> 
>     $var = lazy { return [ 1, 2, 3 ]; };
>     $var[] = 4;
> 
> ---
> 
> Currently it is possible do it in a very hackish way: by using magic
> getter, by create a user getter or a own implementation of this
> feature.
> All this ways have a lot of limitations.
> 
> A hackish example that shows how it should works on current PHP
> version: http://pastebin.com/cz93wL7n
> 
> ---
> 
> I tell more about that here: https://bugs.php.net/bug.php?id=72637
> 
> -- 
> David Rodrigues

In concept I like the idea, especially as it would allow for "optionally
computed values", which is a performance benefit if those values may not
be used.  Think of pulling default values out of configuration in the
database if not provided at runtime; no sense running the query if it
won't be used.  I could also see it having very interesting use cases in
dependency injection containers.

However, that also means there's an enormous potential for race
conditions.  Technically no more than closures now, but the use cases
seem like they'd make it more prevalent.  If you "use" by reference, or
use a mutable object, or a service that depends on IO, etc. then the
resulting value of the lazy variable is not technically
non-deterministic, but will certainly feel like it to the developer.

Is there a way we could provide better safety around that issue?

--Larry Garfield

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to