我需要创建匿名对象并调用它的方法
$obj = new stdClass();
$obj->Greeting = function (string $d){return "Hello ".$d;};
$greetings = $obj->Greeting("world!"); 但是当我试图执行这段代码时,我会得到一个错误。
Call to undefined method stdClass::Greeting()
怎么了?
发布于 2021-11-06 12:36:36
您创建了一个stdClass对象,而不是匿名者
$obj = new class () {
public function Greeting(string $d)
{
return "Hello $d";
}
};
echo $greetings = $obj->Greeting("world!");产出:
Hello world!怎么了?
没什么,让我们问一问,这背后到底发生了什么?
stdClass用于PHP中的“空”对象,或者当将数组转换为对象($obj = (object) ['hello' => 'world'])时。
默认情况下,它没有属性(如$obj = new stdClass;中的属性),也没有方法。从这两个方面来说,都是空的。
属性可以动态地添加到stdClass对象中--但是在实例化对象之前必须在PHP中声明类方法的函数。
因此,在您的例子中,函数是一个属性(PHP在这里有两个包:一个用于属性,一个用于函数),而不是一个动态添加到它的新方法(class MyClass { function method() {...} })。
让我们与原始示例进行比较,并再次引发错误:
$obj = new stdClass();
$obj->Greeting = function (string $d) {
return "Hello $d";
};
$greetings = $obj->Greeting("world!"); PHP Fatal error: Uncaught Error: Call to undefined method stdClass::Greeting()然而:
echo $greetings = ($obj->Greeting)("world!");
# #工程,输出:
Hello world!因为PHP现在被引导为间接地“调用”($obj->Greeting)属性,所以不首先寻找stdClass::Greeting方法。
通常,您不希望这种间接,因此建议使用匿名类代替。
发布于 2021-11-06 12:41:44
变化
$obj->Greeting("world!"); 至
($obj->Greeting)("world!"); 或者使用call_user_func():
call_user_func($obj->Greeting, 'world!')https://stackoverflow.com/questions/69863945
复制相似问题