开发者

$this in callback function

I would like to know why this works:

class Foo {
    public function doSomethingFunny($subject) {
        preg_replace_callback(
            "#pattern#",
            array($this, 'doX'),
            $subject
        );
    }
    private function doX() {
        echo 'why does this work?';
    }
}

Why is the callback sti开发者_运维问答ll within the context of $this? I would expect it the allow only public methods. I'm missing something fundamental in how the callback works.


The callback parameter in preg_replace_callback() allows for the calling of a method, and allows for the passing of an array to tell the method the context of the call back. It's not only $this, but also any object variable.

$foo = new Foo();
preg_replace_callback(
    "#pattern#",
    array($foo, 'bar'),
    $subject
);

In the example above, if Foo::bar() is private, that would not work. However, in your original case, the private method is still triggered because of the use of $this which is in the same context as the private method.


if it's in the same class it's in the same scope/context ($this).


I believe it is implied that a callback executes in the current scope. call_user_func, or any function that uses a callback (such as preg_replace_callback) is intended to programatically emulate the equivalent in-line call. In other words, it must behave that way in order to provide the intended functionality.

Therefore in the following case Foo->A() and Foo->B() should behave the same way, regardless of visibility:

class Foo() {
    function Bar() {
    }

    function A() {
         return $this->Bar();
    }
    function B() {
         return call_user_func(array($this, 'Bar'));
    }
}

It isn’t explicitly documented though, which would be handy.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜