$ 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 still in the context of $ this? I would expect this to only allow public methods. I am missing something fundamental in how the callback works.

+3
source share
3 answers

The callback parameter in preg_replace_callback () allows you to call the method and allows you to pass an array to pass the callback context to the method. This is not only $ this, but also any object variable.

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

In the above example, if Foo :: bar () is private, this will not work. However, in your original case, the private method still runs due to the use of $ this, which is in the same context as the private method.

+5

/ ($ this).

+3

I believe that the callback is implied in the current scope. call_user_func, or any function that uses a callback (for example, preg_replace_callback) is designed to programmatically emulate an equivalent inline call. In other words, it should behave in such a way as to provide the intended functionality.

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

class Foo() {
    function Bar() {
    }

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

This is clearly not documented, but it would be convenient.

+1
source

Source: https://habr.com/ru/post/1794539/


All Articles