Sébastien Morel
Contributed by Sébastien Morel in #34769

Typed properties, introduced in PHP 7.4, are one of the most important features added by PHP in years. In Symfony 5.1 we're implementing new features based on them, such as extracting typed properties info using the PropertyInfo component.

Consider this example using typed properties:

1
2
3
4
5
6
7
8
9
10
11
12
13
use Twig\Environment;

class SomeServiceClass
{
    /** @required */
    public Environment $twig;

    public function someMethod()
    {
        $this->twig->render('...');
        // ...
    }
}

In previous Symfony versions, this example wouldn't work because Twig service is not properly injected. In Symfony 5.1, this example will work as expected. The reason is that Symfony 5.1 autowires all public properties that are typed with classes related to services and which include the @required annotation.

Some things to consider:

  • Only public properties are autowired; protected and private properties will never be autowired to avoid any confusing behavior;
  • This is in practice equivalent to setter injection, which has drawbacks and it should be used only in very specific scenarios.

This new feature is just one of the many tools that Symfony gives you to automate the configuration of how services/objects should be created. If it doesn't fit your way of developing applications, it's OK to keep using the traditional service injection based on constructors and private properties.

Published in #Living on the edge