Search code examples
phpcallbackscope

Can I pass a protected function as a callable?


I have a function which takes a callable parameter:

public static function setup(Router $router, Injector $injector, callable $toRouterCallable): void

I want to call it from another class and pass a protected parent function as the callable parameter. I tried three approaches, but they all fail:

Routes::setup($router, $injector, $this->toRouterCallable); // Undefined property '$toRouterCallable' 
Routes::setup($router, $injector, parent::toRouterCallable); // Undefined class constant 'toRouterCallable'
Routes::setup($router, $injector, [$this, 'toRouterCallable']); // Argument 3 passed setup() must be callable, array given

How can I pass the parent function to this function?


Solution

  • You can use First class callable syntax since PHP 8.1

    Routes::setup($router, $injector, $this->toRouterCallable(...));
    

    You can use the Clousure class before that

    $cl = Closure::fromCallable([$this, 'toRouterCallable']);
    Routes::setup($router, $injector, $cl);