【发布时间】:2014-03-02 12:43:33
【问题描述】:
这似乎不起作用,我不知道为什么? 你可以在非静态方法中创建静态闭包,为什么不反过来呢?
class RegularClass {
private $name = 'REGULAR';
}
class StaticFunctions {
public static function doStuff()
{
$func = function ()
{
// this is a static function unfortunately
// try to access properties of bound instance
echo $this->name;
};
$rc = new RegularClass();
$bfunc = Closure::bind($func, $rc, 'RegularClass');
$bfunc();
}
}
StaticFunctions::doStuff();
// PHP Warning: Cannot bind an instance to a static closure in /home/codexp/test.php on line 19
// PHP Fatal error: Using $this when not in object context in /home/codexp/test.php on line 14
【问题讨论】:
-
嗯,似乎也不适用于
bindTo。 -
来自 bindTo 文档“静态闭包不能有任何绑定对象(参数 newthis 的值应该为 NULL),但是这个函数仍然可以用来改变它们的类范围。” php.net/manual/en/closure.bindto.php ,并且由于 bind 只是 bindTo 的静态,我猜你不能在静态上下文上进行非静态闭包。