Bjoern
Bjoern

Reputation: 16304

callback invoked in class extension

I'm working my way through php callbacks. I think I've covered the basics, but when working within class extensions I'm still hitting a brick wall somewhere for some time now, therefore it is time for some stack overflow rubber duck programming...!

Calling a callback from a class extension:

class myClass {
    function cb_check($function) {
        call_user_func($this->$function);
    }

    static function myFunction() {
        var_dump("Hello World");
    }   
}

class myExtClass extends myClass {
    function cb_invoke() {
        $this->cb_check('myFunction');
    }
}

$x = new myExtClass;
$x->cb_invoke();

Error message (or, notice and warning):

Notice: Undefined property: myExtClass::$myFunction in F:\test.php on line 5

Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in F:\test.php on line 5

Line 5 is the call_user_func() above.

Does anybody have an idea what I am missing here?

Thank you in advance!

Upvotes: 0

Views: 145

Answers (3)

Mike Firesheets
Mike Firesheets

Reputation: 139

Your error arises because you've declared myFunction() to be static. Static methods don't belong to any specific instance of a class and therefore can't be accessed through the $this variable. Instead you use self::myFunction() to call the static method. The easiest way to make this happen is to build the string of the static method call and pass the string as the parameter to call_user_func(). Your code would work as-written if myFunction() were not static.

class myClass {
    function cb_check($function) {
        // Build a static-method-style string
        call_user_func('self::' . $function);
    }

    static function myFunction() {
        var_dump("Hello World");
    }   
}

class myExtClass extends myClass {
    function cb_invoke() {
        $this->cb_check('myFunction');
    }
}

$x = new myExtClass;
$x->cb_invoke();

Upvotes: 1

syed shah
syed shah

Reputation: 678

While working with static classes you should have to use scope resolution operator :: you can not create the instance directly .

$x::myExtClass;

Try it.

Upvotes: 1

Bjoern
Bjoern

Reputation: 16304

As mark pointed out,

call_user_func($this->$function);

should be replaced by either

call_user_func(array($this, $function));

or

call_user_func('self::' . $function);

Thanks, Mark!

Upvotes: 4

Related Questions