Error Identifier: assign.readOnlyPropertyByPhpDoc
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
{
/** @readonly */
private int $value;
public function __construct()
{
$this->value = 1;
$this->value = 2;
}
}
Why is it reported? #
A property marked with the @readonly PHPDoc tag is being assigned more than once. The @readonly annotation indicates that the property should only be assigned in the constructor and must not be modified afterwards. Assigning it multiple times, even within the constructor, violates this contract because the intent is for the property to be set exactly once.
How to fix it #
Remove the duplicate assignment:
<?php declare(strict_types = 1);
class Foo
{
/** @readonly */
private int $value;
public function __construct()
{
- $this->value = 1;
$this->value = 2;
}
}
Or, on PHP 8.1+, use the native readonly modifier instead which enforces single-assignment at the language level:
<?php declare(strict_types = 1);
class Foo
{
- /** @readonly */
- private int $value;
+ private readonly int $value;
public function __construct()
{
$this->value = 1;
- $this->value = 2;
}
}
How to ignore this error #
You can use the identifier assign.readOnlyPropertyByPhpDoc to ignore this error using a comment:
// @phpstan-ignore assign.readOnlyPropertyByPhpDoc
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: assign.readOnlyPropertyByPhpDoc
Rules that report this error #
- PHPStan\Rules\Properties\MissingReadOnlyByPhpDocPropertyAssignRule [1]