skip to Main Content
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


  1. 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.

    Login or Signup to reply.
  2. 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 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search