• 4
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 187

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 187
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Using $this in method called with call_user_func_array

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 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)

  • 14
Reply Report
      • 1
    • Just for the record there is a second mistake in his code, array('id' => 1) should rather be array(1) judging by his definition of bar
      • 2
    • Hah! Should've seen that coming, didn't think it was that simple. Thanks a ton! Regarding your edit: that's a typo, wrote that code in the SO-ask window :-). Thanks again!