开发者

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 开发者_StackOverflowwhat's the syntax that allows you to invoke a function which is stored in a member variable?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜