开发者

Invoking a function from a class member in PHP

开发者 https://www.devze.com 2023-03-28 14:50 出处:网络
Say I have the following: class C { private $f; public function __construct($f) { $this->f = $f; } public function invoke ($n) {

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

精彩评论

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