gpt4 book ai didi

php - 类上下文中的 call_user_func(定义了 $this)

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:03:58 24 4
gpt4 key购买 nike

有没有一种方法可以在对象的上下文中执行 PHP5.3 中的闭包?

class Test {
public $name='John';

function greet(){
eval('echo "Hello, ".$this->name;');

call_user_func(function(){
echo "Goodbye, ".$this->name;
});
}
}
$c = new Test;
$c->greet();

eval() 可以正常工作,但是 call_user_func 将无法访问 $this。 (不在对象上下文中时使用 $this)。我现在将“$this”作为参数传递给闭包,但这并不是我所需要的。

最佳答案

从 PHP 5.3.6 开始,无法从 lambda 或闭包访问 $this。您要么必须将 $this 分配给临时变量并将其与 use 一起使用(这意味着您将只能使用公共(public) API),要么传入/使用想要的属性(property)。所有显示在本网站的其他地方,所以我不会重复。

虽然对于 PHP.next:http://codepad.viper-7.com/PpBXa2,但在 Trunk 中可以访问 $this

关于php - 类上下文中的 call_user_func(定义了 $this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5549724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com