在使用call_user_func_array调用的方法中使用$ this

Zar*_*Zar 9 php arrays oop

我有一个方法,简化如下:

class Foo {

   public function bar($id) {
      // do stuff using $this, error occurs here
   }

}
Run Code Online (Sandbox Code Playgroud)

像这样调用它很有用:

$foo = new Foo();
$foo->bar(1);
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用它call_user_func_array(),就像这样:

call_user_func_array(array("Foo", "bar"), array('id' => 1));
Run Code Online (Sandbox Code Playgroud)

哪个应该相等,我得到以下错误:

致命错误:在不在对象上下文中时使用$ this

($this未定义)

为什么是这样?有什么我想念的吗?我应该怎么做才能$this在被调用的方法中使用?

Thi*_*ter 14

array("Foo", "bar")等于Foo::bar(),即一个静态方法 - 这是有道理的,因为$foo没有使用,因此PHP 无法知道使用哪个实例.

你想要的是array($foo, "bar")调用实例方法.

有关各种callables的列表,请参见http://php.net/manual/en/language.types.callable.php.


您还需要将参数作为索引数组而不是关联数组传递,即array(1)代替array('id' => 1)