php通过字符串名称调用类函数 [英] php call class function by string name

查看:149
本文介绍了php通过字符串名称调用类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过其名称调用普通(非静态)类函数?

How can I call a normal (not static) class function by its name?

下面给出一个错误,指出参数1必须是有效的回调.我不希望函数是静态的,我希望它是普通的函数,到目前为止,我所看到的所有示例都将它们设为静态.

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');

推荐答案

callback 语法在PHP中有点奇怪.您需要做的是创建一个数组.第一个元素是对象,第二个元素是方法.

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'));

您也可以在没有call_user_func的情况下这样做:

You can also do it without call_user_func:

$player->{'SayHi'}();

或者:

$method = 'SayHi';
$player->$method();

这篇关于php通过字符串名称调用类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆