Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call_user_func() expects parameter 1 to be a valid callback

Tags:

dictionary

php

I'm just playing around with the call_user_func function in PHP and am getting this error when running this simple code:

<?php


class A
{

    public $var;
    private function printHi()
    {

        echo "Hello";   

    }

    public function __construct($string)
    {
        $this->var = $string;   


    }

    public function foo()
    {

        call_user_func($this->var); 

    }

}

$a = new A('printHi');
$a->foo();


?>

I know that if I make a function outside the class called printHi, it works fine, but I'm referring to the class's print hi and not sure why the "this" isn't being registered.

like image 233
thed0ctor Avatar asked Nov 13 '12 18:11

thed0ctor


2 Answers

$this->var is evaluating to printHi in your example. However, when you are calling a method of a class, you need to pass the callback as an array where the first element is the object instance and the second element is the function name:

call_user_func(array($this, $this->var));

Here is the documentation on valid callbacks: http://www.php.net/manual/en/language.types.callable.php

like image 119
DiverseAndRemote.com Avatar answered Oct 22 '22 13:10

DiverseAndRemote.com


Alternatively to Omar's answer, you can also make printHi() a class static function, so you then can call it from call_user_func('A::printHi') , like this:

class A
{

    public $var;
    public static function printHi()
    {

        echo "Hello";   

    }

    public function __construct($string)
    {
        $this->var = $string;   


    }

    public function foo()
    {

        call_user_func($this->var); 

    }

}

$a = new A('A::printHi');
$a->foo();

See live example

like image 44
Nelson Avatar answered Oct 22 '22 14:10

Nelson