php通过字符串名称调用类的功能(php call class function by string name)

编程入门 行业动态 更新时间:2024-10-28 03:32:24
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();

更多推荐

本文发布于:2023-07-22 19:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222831.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   名称   功能   php   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!