bar(function () { $this->pr" /> bar(function () { $this->pr" /> bar(function () { $this->pr"/>

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

80 Views Asked by At
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?

2

There are 2 best solutions below

0
KIKO Software On BEST ANSWER

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.

0
mickmackusa On

Without adjusting your class at all, you can simply pass the class and method name as an array to represent the callable. This technique doesn't offer the ability to pass parameters into the callback.

Code: (Demo)

$foo = new foo();
$foo->bar([$foo, 'printStr']);

Or you can use arrow function syntax in an anonymous function to call the class method. This is helpful when parameters need to be passed into the callback.

Code: (Demo)

$foo = new foo();
$foo->bar(fn() => $foo->printStr());

Both of these approaches are appropriate if the callable doesn't need to access class methods (or objects or constants) 100% of the time. If your bar() method's callable will ALWAYS need access to the instantiated object, then @KIKOSoftware's advice to modify the class is most appropriate.