symfonysymfony6

Can not access parameters in controller class constructor


When I try to set a class property from the parameterBag in the class constructor, like so:

public function __construct()
{
    $this->foo = $this->getParameter('app.foo');
}

I get

Call to a member function has() on null

I wonder if it's possible to access parameters defined in config/services.yaml in the constructor of a controller ?


Solution

  • You can use the #[Autowire] attribute

    public function __construct(#[Autowire(param: 'app.foo')] private readonly string $foo)
    {
    }
    

    Symfony documentation