Error Identifier: property.uninitializedReadonly
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
{
private readonly int $assigned;
private readonly int $unassigned;
public function __construct()
{
$this->assigned = 1;
}
}
Why is it reported? #
A readonly property must be initialized exactly once during the object’s construction. If a readonly property is not assigned in the constructor (or in a method configured as an additional constructor), it will remain uninitialized. Accessing an uninitialized readonly property at runtime throws an Error.
In the example above, $unassigned is declared as readonly but is never assigned in the constructor, so it will remain uninitialized.
This error is also reported when a readonly property is accessed before it has been assigned within the constructor, since the property is still in an uninitialized state at that point.
How to fix it #
Assign the readonly property in the constructor:
<?php declare(strict_types = 1);
class Foo
{
private readonly int $assigned;
private readonly int $unassigned;
public function __construct()
{
$this->assigned = 1;
+ $this->unassigned = 2;
}
}
Or use constructor promotion to ensure the property is always initialized:
<?php declare(strict_types = 1);
class Foo
{
- private readonly int $assigned;
-
- private readonly int $unassigned;
-
- public function __construct()
- {
- $this->assigned = 1;
- }
+ public function __construct(
+ private readonly int $assigned,
+ private readonly int $unassigned,
+ ) {}
}
If the property is initialized in a method other than __construct, configure that method as an additional constructor using the additionalConstructors configuration parameter.
How to ignore this error #
You can use the identifier property.uninitializedReadonly to ignore this error using a comment:
// @phpstan-ignore property.uninitializedReadonly
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: property.uninitializedReadonly