我可以用变量调用方法吗? [英] Can I call methods with variables?
本文介绍了我可以用变量调用方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在PHP中执行以下操作吗?
Can I do the following in PHP?
$lstrClassName = 'Class';
$lstrMethodName = 'function';
$laParameters = array('foo' => 1, 'bar' => 2);
$this->$lstrClassName->$lstrMethodName($laParameters);
我现在使用的解决方案是通过eval()调用函数,如下所示:
The solution I'm using now, is by calling the function with eval() like so:
eval('$this->'.$lstrClassName.'->'.$lstrMethodName.'($laParameters);');
我很好奇是否有更好的方法可以解决这个问题.
I'm curious if there is a beter way to solve this.
谢谢!
推荐答案
您不需要评估...取决于您的版本
You don't need eval to do that ... depending on your version
示例
class Test {
function hello() {
echo "Hello ";
}
function world() {
return new Foo ();
}
}
class Foo {
function world() {
echo " world" ;
return new Bar() ;
}
function baba() {
}
}
class Bar {
function world($name) {
echo $name;
}
}
$class = "Test";
$hello = "hello";
$world = "world";
$object = new $class ();
$object->$hello ();
$object->$world ()->$world ();
$object->$world ()->$world ()->$world(" baba ");
输出
Hello World baba
如果您使用的是PHP 5.4,则可以直接调用它而不必声明变量
And if you are using PHP 5.4 you can just call it directly without having to declare variables
您可能还希望查看call_user_func
http://php.net/manual/en/function.call-user-func.php
这篇关于我可以用变量调用方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文