简体   繁体   中英

use service invoke function in symfony

Is possible to call invoke function from a service in symfony?

this is the controller

class FooController extends AbstractController
{
    private $fooService;

    public function __construct(FooService $fooService)
    {
        $this->fooService = $fooService;
    }

    #[Route('/foo', name: 'app_foo')]
    public function index(): Response
    {
       
        return new Response($this->fooService->__invoke());
        //is not possible to do 
        //return new Response($this->fooService());
    }
}

and the service

namespace App\Service;

class FooService
{
    public function __invoke()
    {
        return 'hello';
    }
}

I have to call __invoke function explicitly instead to make $ this->fooService() is not possible to do it?

In PHP the method call has higher priority than property access so you need to use parentheses.

($this->fooService)()

To access the property and call it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM