简体   繁体   中英

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!

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!

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

$x::myExtClass;

Try it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM