Lazy evaluation of any closure in PHP

I'm looking for a context-independent lazy evaluation of Closure. In pseudocode:

// imagine there a special type of "deferred" variables
$var = (deferred) function () {
    // do something very expensive to calculate
    return 42;
};

// do something else - we do not need to know $var value here,
// or may not need to know it at all

var_dump($var * 2);
// after some million years it prints: int(84)

// now this is the hardest part...
var_dump($var); // notice no brackets here
// prints immediately as we already know it: int(42)

      

The last step is crucial: this way we can pass a variable (or a member of a class) without knowing that it actually is to the point that they use it.

It is clear that I cannot do the same directly in the language, because even with magic methods __toString()

it will not replace the original value. Even it won't work with anything other than the lines:

// this will fail
function __toString()
{
    return new Something();
}

      

Of course, I can wrap the Closure with another object, but that means everyone on the stack needs to know how to deal with it. And this is what I want to avoid.

Is this even remotely possible? Maybe there's a hacked PECL out there somewhere to do this or something similar.

+3


source to share


1 answer


I think you need scraps.

http://en.wikipedia.org/wiki/Memoization

This is one of those undocumented features in PHP. Basically you declare a static variable in the closure and use it as a cache.

$var = function(){
    static $foo; // this is a memo, it sticks only to the closure
    if (isset($foo)) return $foo;
    $foo = expensive calculation
    return $foo;
};

var_dump($var()); // millions of years
var_dump($var()); // instant

      



This will lazily evaluate and cache calculations.

If you mean "defer" like running them in the background, you can't because PHP is not multithreaded. You will need to set up multiprocess workers or use pthreads.

http://php.net/manual/en/book.pthreads.php

+1


source







All Articles