Error Identifier: symfonyContainer.privateService
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
This error is reported by phpstan/phpstan-symfony.
Code example #
<?php declare(strict_types = 1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
public function index(): Response
{
$mailer = $this->container->get('app.mailer');
return new Response('OK');
}
}
Why is it reported? #
The service being fetched from the Symfony dependency injection container is configured as private. Private services cannot be retrieved directly from the container using get(). They are only available through dependency injection (autowiring or explicit configuration). Attempting to fetch a private service at runtime will throw an exception.
How to fix it #
Inject the service through the constructor or method injection instead of fetching it from the container.
<?php declare(strict_types = 1);
namespace App\Controller;
+use App\Service\Mailer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
- public function index(): Response
+ public function __construct(
+ private Mailer $mailer,
+ ) {
+ }
+
+ public function index(): Response
{
- $mailer = $this->container->get('app.mailer');
+ $this->mailer->send();
return new Response('OK');
}
}
How to ignore this error #
You can use the identifier symfonyContainer.privateService to ignore this error using a comment:
// @phpstan-ignore symfonyContainer.privateService
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: symfonyContainer.privateService
Rules that report this error #
- PHPStan\Rules\Symfony\ContainerInterfacePrivateServiceRule [1] phpstan/phpstan-symfony