php php通过字符串名称调用类函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16740112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php call class function by string name
提问by user441521
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.
下面给出了一个错误,指出 param 1 需要是一个有效的回调。我不希望函数是静态的,我希望它是一个普通的函数,到目前为止我看到的所有例子都是静态的。
class Player
{
public function SayHi() { print("Hi"); }
}
$player = new Player();
call_user_func($Player, 'SayHi');
回答by Rocket Hazmat
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.
callback
PHP 中的语法有点奇怪。您需要做的是创建一个数组。第一个元素是对象,第二个元素是方法。
call_user_func(array($player, 'SayHi'));
You can also do it without call_user_func
:
你也可以不这样做call_user_func
:
$player->{'SayHi'}();
Or:
或者:
$method = 'SayHi';
$player->$method();
回答by meagar
回答by Toskan
I am giving my answer to a different question here ( PHP - Can you assign a member function to a variable?), because it was marked as duplicate by some stackoverflow radicals, and I cannot give my answer to his question! The mentality of stackoverflow fanatics needs to stop.
我在这里回答一个不同的问题(PHP - 你可以给变量分配一个成员函数吗?),因为它被一些 stackoverflow 部首标记为重复,我不能回答他的问题!stackoverflow 狂热分子的心态需要停止。
btw generally this is anti pattern:
顺便说一句,这通常是反模式:
$a = 'Pl';
$b = 'aye';
$c = 'r';
$z = $a . $b . $c;
$myz = new $z();
$d = 'Say';
$e = 'Hi';
$x = $d.$e;
$myz->{$x}()
now spread out all variables across your code. You have become the anti christ.
现在将所有变量分布在您的代码中。你已经成为了敌基督。
why? because nobody can read your code any longer. Including yourself.
为什么?因为没有人可以再读你的代码了。包括你自己。
Better is to have the actual references in your code to the function calls you make. Not hidden in some obscure strings. No, just standard calls to the code, wrapped into a function.
更好的是在您的代码中包含对您进行的函数调用的实际引用。不隐藏在一些晦涩的字符串中。不,只是对代码的标准调用,包装成一个函数。
Try to keep it as simple as possible. So a better solution would be this:
尽量保持简单。所以更好的解决方案是这样的:
$x = function(){
$player = new Player();
$player->sayHi();
};
$x();
your IDE will find those references. $myz->{$x}()
your IDE will not find and you wont be able to maintain well your code
您的 IDE 将找到这些引用。$myz->{$x}()
您的 IDE 将找不到,您将无法很好地维护您的代码
回答by Nagarjun
You are anyway creating an object of the class, so you can use object to call its function.
无论如何,您都是在创建类的对象,因此您可以使用 object 来调用其函数。
$player = new Player();
$player->SayHi();
or use callback
或使用回调
$player = new Player();
call_user_func(array($player, 'SayHi'));
回答by zeyorama
$player->SayHi();
$player->SayHi();
I prefer this form.
我更喜欢这种形式。