Error Identifier: assign.propertyReadOnly
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(
public readonly string $name,
)
{
}
}
$foo = new Foo('bar');
$foo->name = 'baz';
Why is it reported? #
A value is being assigned to a property that is not writable. This typically happens when writing to a readonly property outside its initialization context, or to a property that only defines a get hook without a set hook.
In the example above, the property $name is declared as readonly and has already been initialized in the constructor. Attempting to assign a new value to it outside the constructor is not allowed.
How to fix it #
Avoid assigning to the property after it has been initialized. If you need to change the value, create a new instance instead:
<?php declare(strict_types = 1);
$foo = new Foo('bar');
-$foo->name = 'baz';
+$foo = new Foo('baz');
How to ignore this error #
You can use the identifier assign.propertyReadOnly to ignore this error using a comment:
// @phpstan-ignore assign.propertyReadOnly
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.propertyReadOnly
Rules that report this error #
- PHPStan\Rules\Properties\WritingToReadOnlyPropertiesRule [1]