在PHP中使用call_user_func_数组调用非静态方法
我试图用call_user_func_数组调用一个对象的非静态方法,但我不理解如何构造回调。我在网上找到了很多类似的例子,但没有一个和我遇到的完全一样。在PHP中使用call_user_func_数组调用非静态方法,php,Php,我试图用call_user_func_数组调用一个对象的非静态方法,但我不理解如何构造回调。我在网上找到了很多类似的例子,但没有一个和我遇到的完全一样。 class DBCommand { private $db; // The DBConnection object function __construct() { $db = new DBConnection(); } function callMethod($method, $argume
class DBCommand {
private $db; // The DBConnection object
function __construct() {
$db = new DBConnection();
}
function callMethod($method, $arguments) {
// This line gives me the error:
return call_user_func_array(array($this->db, "$method"), $arguments);
}
}
?>
使用DBConnection方法的名称及其正确的参数调用callMethod可以实现以下目的
PHP Warning: call_user_func_array() expects parameter 1 to be a valid
callback, first array member is not a valid class name or object
因此,callMethod返回null。使用符号
[$objectHandle,“methodName”]
动态调用非静态方法:
call_user_func_array([$this,$method], $arguments);
使用符号
[$objectHandle,“methodName”]
动态调用非静态方法:
call_user_func_array([$this,$method], $arguments);
$this->db=newdbconnection()代码>在构造函数中。当前,您只将连接对象分配给一个局部变量,而不分配给对象字段。请注意,您不需要引用该变量。只要$method
就行了。@csstudent当您实例化DBConnection
$this->db=new DBConnection()时,您将遇到无限递归代码>在构造函数中。当前,您只将连接对象分配给一个局部变量,而不分配给对象字段。请注意,您不需要引用该变量。只要$method
就行了。@csstudent当您实例化DBConnection
时,您将遇到无限递归。这个问题是关于非静态的methods@BeetleJuice实际上没有无限递归。DBCommand!=DBConnectionMy bad我把OP类的名称误读为DBConnection
,当它是DBCommand
时。我已经从我的答案中删除了那个注释。这个问题是关于非静态的methods@BeetleJuice实际上没有无限递归。DBCommand!=DBConnectionMy bad我把OP类的名称误读为DBConnection
,当它是DBCommand
时。我已经把那张纸条从我的答案中删除了。