Cod*_*eXP 8 php binding closures
这似乎不起作用,我不知道为什么?你可以在非静态方法中创建静态闭包,为什么不反之呢?
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
Run Code Online (Sandbox Code Playgroud)
正如我在评论中所说,似乎你无法从静态上下文的闭包中更改"$ this". "静态闭包不能有任何绑定对象(参数newthis的值应该为NULL),但是这个函数可以用来改变它们的类范围." 我想你必须做这样的事情:
class RegularClass {
private $name = 'REGULAR';
}
class Holder{
public function getFunc(){
$func = function ()
{
// this is a static function unfortunately
// try to access properties of bound instance
echo $this->name;
};
return $func;
}
}
class StaticFunctions {
public static function doStuff()
{
$rc = new RegularClass();
$h=new Holder();
$bfunc = Closure::bind($h->getFunc(), $rc, 'RegularClass');
$bfunc();
}
}
StaticFunctions::doStuff();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2807 次 |
最近记录: |