Error Identifier: constructor.call
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.
Code example #
<?php declare(strict_types = 1);
class Foo
{
public function __construct(private string $name)
{
}
public function reinitialize(string $name): void
{
$this->__construct($name);
}
}
Why is it reported? #
This error is reported by phpstan/phpstan-strict-rules.
Calling __construct() on an already-constructed object is not a standard practice in PHP. The constructor is intended to be called once during object creation via new. Re-calling it can lead to unexpected behavior because it bypasses the normal object lifecycle.
Similarly, static calls to __construct() (e.g. SomeClass::__construct()) are only appropriate as parent::__construct() calls within a child class constructor. Calling another class’s constructor statically from outside that context is a code smell.
How to fix it #
Use a dedicated method or a factory pattern instead of re-calling the constructor:
<?php declare(strict_types = 1);
class Foo
{
public function __construct(private string $name)
{
}
- public function reinitialize(string $name): void
+ public function withName(string $name): self
{
- $this->__construct($name);
+ return new self($name);
}
}
How to ignore this error #
You can use the identifier constructor.call to ignore this error using a comment:
// @phpstan-ignore constructor.call
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: constructor.call