Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $this in method called with call_user_func_array

Tags:

arrays

oop

php

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?

like image 466
Zar Avatar asked Oct 14 '12 19:10

Zar


1 Answers

array("Foo", "bar") is equal to Foo::bar(), i.e. a static method - this makes sense since $foo is 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 of array('id' => 1)

like image 170
ThiefMaster Avatar answered Nov 12 '22 05:11

ThiefMaster