sanmai
sanmai

Reputation: 30911

Lazy evaluation of any Closure in PHP

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

// imagine there's 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)

Last step is crucial: such way we can pass a variable (or a class member) around without anyone knowing what it actually is up to the point they're using it.

Clearly I can't do exactly that right in the language, because even with strings __toString() magic method would not replace the original value. Not even it's going to work with anything else than strings:

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

Sure, I can wrap around a Closure with another object, but this means everyone up the stack would have to know how to deal with it. And this is what I'm looking to avoid.

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

Upvotes: 4

Views: 1254

Answers (1)

y o
y o

Reputation: 1163

I think what you want are memos.

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

This is one of those undocumented features in PHP. Basically you declare a static variable within 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 lazy evaluate and cache the calculation.

If you mean "defer" as in run them in the background, you can't because PHP is not multi-threaded. You would have to set up multi-process workers or use pthreads.

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

Upvotes: 3

Related Questions