Search code examples
phpfirst-class-functions

Invoking a function from a class member in PHP


Say I have the following:

class C {
    private $f;

    public function __construct($f) {
        $this->f = $f;
    }

    public function invoke ($n) {
        $this->f($n); // <= error thrown here
    }
}

$c = new C(function ($m) {
    echo $m;
});

$c->invoke("hello");

The above throws the following error:

Fatal error: Call to undefined method C::f()

And I'm guessing that it's because I'm trying to invoke the callback function $this->f using the same syntax one would invoke an object's member functions.

So what's the syntax that allows you to invoke a function which is stored in a member variable?


Solution

  • You need to use call_user_func:

    public function invoke ($n) {
        call_user_func($this->f, $n);
    }
    

    UPDATE

    Christian points out that call_user_func is very slow, and that this is faster:

    function my_call_user_func($f) {
        $f();
    }