Error Identifier: property.uninitializedReadonlyByPhpDoc
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 User
{
/** @readonly */
public string $name; // ERROR: Class User has an uninitialized @readonly property $name. Assign it in the constructor.
public function __construct()
{
}
}
Why is it reported? #
A property marked with the @readonly PHPDoc tag is not assigned a value in the constructor. Properties annotated as @readonly should be initialized in the constructor (or via a default value) because they cannot be assigned later. Leaving a @readonly property uninitialized means it will never receive a value, which defeats the purpose of the property.
This rule also reports access to an uninitialized @readonly property before it has been assigned in the constructor.
How to fix it #
Assign the property in the constructor:
<?php declare(strict_types = 1);
class User
{
/** @readonly */
public string $name;
- public function __construct()
+ public function __construct(string $name)
{
+ $this->name = $name;
}
}
Or provide a default value:
<?php declare(strict_types = 1);
class User
{
/** @readonly */
- public string $name;
+ public string $name = 'default';
public function __construct()
{
}
}
If the property should not be @readonly, remove the annotation:
<?php declare(strict_types = 1);
class User
{
- /** @readonly */
public string $name;
public function __construct()
{
}
}
How to ignore this error #
You can use the identifier property.uninitializedReadonlyByPhpDoc to ignore this error using a comment:
// @phpstan-ignore property.uninitializedReadonlyByPhpDoc
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.uninitializedReadonlyByPhpDoc