php – 如何将静态函数内创建的闭包绑定到实例
发布时间:2020-12-13 18:00:58 所属栏目:PHP教程 来源:网络整理
导读:这似乎不起作用,我不知道为什么? 你可以在非静态方法中创建静态闭包,为什么不反之呢? class RegularClass { private $name = 'REGULAR';}class StaticFunctions { public static function doStuff() { $func = function () { // this is a static function
|
这似乎不起作用,我不知道为什么?
你可以在非静态方法中创建静态闭包,为什么不反之呢? 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
正如我在评论中所说,似乎你无法从静态上下文的闭包中更改“$this”.
“Static closures cannot have any bound object (the value of the parameter newthis should be NULL),but this function can nevertheless be used to change their class scope.” 我想你必须做这样的事情: 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(),'RegularClass');
$bfunc();
}
}
StaticFunctions::doStuff();
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
