我可以在 PHP 中执行以下操作吗?
$lstrClassName = 'Class';
$lstrMethodName = 'function';
$laParameters = array('foo' => 1, 'bar' => 2);
$this->$lstrClassName->$lstrMethodName($laParameters);
我现在使用的解决方案是像这样用 eval() 调用函数:
eval('$this->'.$lstrClassName.'->'.$lstrMethodName.'($laParameters);');
我很好奇是否有更好的方法来解决这个问题。
谢谢!
最佳答案
你不需要 eval 来做到这一点......取决于你的版本
例子
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,您可以直接调用它而无需声明变量
您可能还想查看 call_user_func
http://php.net/manual/en/function.call-user-func.php
关于php - 我可以用变量调用方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10030355/