I have a method, which simplified looks like this:
class Foo {
public function bar($id) {
// do stuff using $this, error occurs here
}
}
Calling it like this works great:
$foo = new Foo();
$foo->bar(1);
However, if I call it using call_user_func_array(), like this:
call_user_func_array(array("Foo", "bar"), array('id' => 1));
Which should be equal, I get the following error:
Fatal error: Using $this when not in object context in
($this is undefined)
Why is this? Is there something I am missing? How should I do this so I still can use $this in the called method?
array("Foo", "bar")is equal toFoo::bar(), i.e. a static method – this makes sense since$foois nowhere used and thus PHP cannot know which instance to use.What you want is
array($foo, "bar")to call the instance method.See http://php.net/manual/en/language.types.callable.php for a list of the various callables.
You also need to pass the arguments as an indexed array instead of an associative array, i.e.
array(1)instead ofarray('id' => 1)