5

I'm trying to call an object's non-static method with call_user_func_array but I'm not understanding how to formulate the callback. I've found a lot of similar examples online but nothing quite like what I'm running into.

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);
    }
}
?>

Calling callMethod with the name of a DBConnection method and its proper arguments gives me this

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

And because of this, callMethod returns null.

3
  • 1
    $this->db = new DBConnection(); in constructor. Currently you assign a connection object to just a local variable, not to an object field. Commented Jul 19, 2016 at 22:58
  • 1
    Side note, you don't need to quote the variable. Just $method will work. Commented Jul 19, 2016 at 23:00
  • @csstudent you will run into an infinite recursion when you instantiate DBConnection. Commented Jul 19, 2016 at 23:50

2 Answers 2

6

Use the notation [$objectHandle, "methodName"] to dynamically call a non-static method:

call_user_func_array([$this,$method], $arguments);

Live demo

Sign up to request clarification or add additional context in comments.

3 Comments

The question asks about non static methods
@BeetleJuice Actually there's no infinite recursion. DBCommand != DBConnection
My bad I misread OP class's name as DBConnection when it's DBCommand. I've removed that note from my answer.
0

In my case, I was trying to handle that in a controller method calling in a MVC structure

What worked for me was creating a new instance of the class that the desired method to call exists in and passing that instance instead of calling directly from the parent class:

   $controller = new $controller(); 
   call_user_func_array([$controller, $this->method], $this->params);

As it will produce a Fatal Error if the method being called is non-static :

Fatal error: Uncaught TypeError: call_user_func_array(): Argument #1 ($callback) must be a valid callback, non-static method $ClassController::desiredMethod() cannot be called statically

Try to work with static methods or use this approach (new-instance) for whoever faces a similar problem!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.