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
Answers
How about this:
DEMO: https://3v4l.org/VbnNH
Here the
$this
is supplied as an argument to the callable function.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)
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)
Both of these approaches are appropriate if the callable doesn’t need to access class methods 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.