PHP - 动态引用对象函数


PHP - Dynamically reference object function

我不确定这是否可能,但我正在尝试动态调用Test类中名为Dropdown()的函数

通过这样做,我能够动态引用我的public $Store;变量。

$model=new Test;
$lol = 'Store';
echo $model->{$lol}; 

但是当我尝试在类中调用函数Dropdown()时,我收到一个错误Property "Test.Dropdown()" is not defined.

$model=new Test;
$lol = 'Dropdown()';
echo $model->{$lol};

如何在 Test 类中动态调用函数?

使用 $model->{$lol}() 调用该方法:

$className = 'Test'; //additional dynamic class call, if needed example for that too.
$class = new $className();
$method = 'Dropdown';
$class->{$method}();

您可以使用函数call_user_func()或像这样的call_user_func_array()

class Test {
    public function Dropdown($text) {
        echo($text);
    }
}
$class  = 'Test';           // class name
$method = 'Dropdown';       // only the method name, the '()' is part of the PHP syntax
$param  = "Hello world'n";  // parameter
call_user_func([$class, $method], $param);