PHP class method callback


Given class MyClass:

class MyClass {}

To create a callback function that takes a callable argument:

class MyClass
{
    public function callback(callable $func): void
    {
        $func();
    }
}

To create a method that calls the callback function:

class MyClass
{
    public function callback(callable $func): void
    {
        $func();
    }

    public function method(): void
    {
        $this->callback(function () {
            echo 'Hello, World!';
        });
    }
}

Instantiate the class and call method and callback:

$myClass = new MyClass();
$myClass->method(); // Hello, World!
$myClass->callback(function () { echo 42; }); // 42


Please support this site and join our Discord!