如何在 PHP 中动态调用类中的方法?
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
在 PHP 中,可以使用 call_user_func()
或 call_user_func_array()
函数来动态调用类的方法。以下是一个简单的例子:
class MyClass {
public function myMethod($arg) {
echo "Method called with argument: " . $arg;
}
}
// 动态调用类的方法
$classInstance = new MyClass();
$methodName = 'myMethod';
$args = ['some argument'];
call_user_func_array([$classInstance, $methodName], $args);
如果方法不需要参数,可以使用 call_user_func()
:
call_user_func([$classInstance, $methodName]);
请确保传递给 call_user_func_array()
或 call_user_func()
的方法名是存在于指定类实例中的。
评论已关闭