php通过字符串名称调用类的功能(php call class function by string name)
我怎样才能通过它的名字来调用一个普通的(不是静态的)类函数?
下面给出了一个错误,说param 1需要是一个有效的回调。 我不希望函数是静态的,我希望它是一个正常的函数,到目前为止我看到的所有例子都是静态的。
class Player { public function SayHi() { print("Hi"); } } $player = new Player(); call_user_func($Player, 'SayHi');How can I call a normal (not static) class function by its name?
The below gives an error saying param 1 needs to be a valid callback. I don't want the function to be static, I want it to be a normal function, and all the examples I've seen so far had them static.
class Player { public function SayHi() { print("Hi"); } } $player = new Player(); call_user_func($Player, 'SayHi');最满意答案
PHP中的callback语法有点奇怪。 你需要做的是做一个数组。 第一个元素是对象,第二个是方法。
call_user_func(array($player, 'SayHi'));您也可以在不使用call_user_func情况下执行此操作:
$player->{'SayHi'}();要么:
$method = 'SayHi'; $player->$method();The callback syntax is a little odd in PHP. What you need to do is make an array. The 1st element is the object, and the 2nd is the method.
call_user_func(array($player, 'SayHi'));You can also do it without call_user_func:
$player->{'SayHi'}();Or:
$method = 'SayHi'; $player->$method();更多推荐
发布评论