懒惰评估PHP中的任何Closure

时间:2014-10-29 02:35:24

标签: php closures lazy-evaluation

我正在寻找与上下文无关的延迟闭包评估。在伪代码中:

// 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)

最后一步是至关重要的:这样我们可以传递一个变量(或一个类成员),而不知道它实际上是什么,直到他们正在使用它。

显然,我无法在语言中做到这一点,因为即使使用字符串__toString(),魔术方法也不会取代原始值。除了字符串之外,它甚至不能用于其他任何事情:

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

当然,我可以使用另一个对象包裹Closure,但这意味着堆栈中的每个人都必须知道如何处理它。这就是我要避免的。

这甚至可以远程实现吗?也许在某个地方有一个hacky PECL来做这个或类似的东西。

1 个答案:

答案 0 :(得分:1)

我认为你想要的是备忘录。

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

这是PHP中未记录的功能之一。基本上你在闭包中声明一个静态变量,并将其用作缓存。

$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

这将懒惰评估并缓存计算。

如果你的意思是“延迟”,就像在后台运行它们一样,你不能因为PHP不是多线程的。您必须设置多进程工作程序或使用pthreads。

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