【问题标题】:Pass variable to method name in PHP将变量传递给 PHP 中的方法名称
【发布时间】:2014-12-31 02:02:35
【问题描述】:
我尝试在变量中调用我想要的部分名称的方法。我该怎么做,因为我现在拥有的代码不起作用?
$actionName = 'Index';
// object creating...
$action = 'action' . $actionName();
$object->$action;
错误:
Fatal error: Call to undefined function index() in ...
【问题讨论】:
标签:
php
variables
methods
call
【解决方案1】:
您不能以这种方式调用 PHP 方法。您需要使用call_user_func 来执行此操作。
例子:
call_user_func([$object, 'action' . $actionName]/*,$param1, $param2, $param3*/)
// ^ Callable ^ Optional parameters
【解决方案2】:
您需要将 () 添加到变量方法调用中。
$actionName = 'Index';
$object->{"action" . $actionName}();
// or
$action = 'action' . $actionName;
$object->$action();
例子:
class test { function sts() { return "hey"; } }
$tst = new test;
$met = "sts";
echo $tst->$met();