Error Identifier: property.readOnlyByPhpDocAssignByRef
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
{
/**
* @var int
* @readonly
*/
public $value;
public function __construct(int $value)
{
$this->value = $value;
}
public function doFoo(): void
{
$ref = &$this->value; // ERROR: @readonly property Foo::$value is assigned by reference.
}
}
Why is it reported? #
A property marked with the @readonly PHPDoc annotation is being assigned by reference. When a variable holds a reference to a property, the property’s value can be changed through that reference, which violates the @readonly contract. Even if the code does not intend to modify the property through the reference, the reference itself creates a pathway for mutation.
How to fix it #
Read the property value into a regular variable instead of creating a reference:
<?php declare(strict_types = 1);
class Foo
{
public function doFoo(): void
{
- $ref = &$this->value;
+ $ref = $this->value;
}
}
If the property should actually be mutable, remove the @readonly annotation:
<?php declare(strict_types = 1);
class Foo
{
/**
* @var int
- * @readonly
*/
public $value;
}
How to ignore this error #
You can use the identifier property.readOnlyByPhpDocAssignByRef to ignore this error using a comment:
// @phpstan-ignore property.readOnlyByPhpDocAssignByRef
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.readOnlyByPhpDocAssignByRef
Rules that report this error #
- PHPStan\Rules\Properties\ReadOnlyByPhpDocPropertyAssignRefRule [1]