我可以用变量调用方法吗?
问题描述:
我可以在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