如何调用匿名对象php的方法?
How to call a method of anonymous object php?
我需要创建匿名对象并调用它的方法
$obj = new stdClass();
$obj->Greeting = function (string $d){return "Hello ".$d;};
$greetings = $obj->Greeting("world!");
但是当我尝试执行这段代码时出现错误
Call to undefined method stdClass::Greeting()
怎么了?
您创建了一个 stdClass 对象,而不是 anonymous one:
$obj = new class () {
public function Greeting(string $d)
{
return "Hello $d";
}
};
echo $greetings = $obj->Greeting("world!");
输出:
Hello world!
What's wrong?
没什么,我们就问一下,这里发生了什么?
stdClass 用于 PHP 中的“空”对象或将数组转换为对象时 ($obj = (object) ['hello' => 'world']
)。
默认情况下,它没有属性(如 $obj = new stdClass;
),也没有方法。这两个方面都是空的。
属性可以动态添加到 stdClass
对象 - 但不能作为 class 方法的功能,必须在实例化对象之前在 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
方法。
通常您不需要这种间接寻址,因此建议改用匿名 class。
改变
$obj->Greeting("world!");
至
($obj->Greeting)("world!");
或使用call_user_func() :
call_user_func($obj->Greeting, 'world!')
我需要创建匿名对象并调用它的方法
$obj = new stdClass();
$obj->Greeting = function (string $d){return "Hello ".$d;};
$greetings = $obj->Greeting("world!");
但是当我尝试执行这段代码时出现错误
Call to undefined method stdClass::Greeting()
怎么了?
您创建了一个 stdClass 对象,而不是 anonymous one:
$obj = new class () {
public function Greeting(string $d)
{
return "Hello $d";
}
};
echo $greetings = $obj->Greeting("world!");
输出:
Hello world!
What's wrong?
没什么,我们就问一下,这里发生了什么?
stdClass 用于 PHP 中的“空”对象或将数组转换为对象时 ($obj = (object) ['hello' => 'world']
)。
默认情况下,它没有属性(如 $obj = new stdClass;
),也没有方法。这两个方面都是空的。
属性可以动态添加到 stdClass
对象 - 但不能作为 class 方法的功能,必须在实例化对象之前在 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
方法。
通常您不需要这种间接寻址,因此建议改用匿名 class。
改变
$obj->Greeting("world!");
至
($obj->Greeting)("world!");
或使用call_user_func() :
call_user_func($obj->Greeting, 'world!')