phpcallable

How to access $this in the context of a callable outside of class scope?


class foo {
    function bar(callable $callable) {
        $callable();
    }

    function printStr() {
        echo "hi";
    }
}

$foo = new foo();
$foo->bar(function () {
    $this->printStr(); // Using $this when not in object context
});

Yes, you need to pass an anonymous function in which to call the method of the foo class. As in JS. How can this be achieved?


Solution

  • How about this:

    class foo {
        function bar(callable $callable) {
            $callable($this);
        }
    
        function printStr() {
            echo "hi";
        }
    }
    
    $foo = new foo();
    $foo->bar(function ($that) {
        $that->printStr(); // Using $this when not in object context
    });
    

    DEMO: https://3v4l.org/VbnNH

    Here the $this is supplied as an argument to the callable function.