website/errors/property.readOnlyByPhpDocAssignNotOnThis.md
<?php declare(strict_types = 1);
class Foo
{
/** @readonly */
public int $value;
public function __construct(self $other)
{
$other->value = 10; // ERROR: @readonly property Foo::$value is not assigned on $this.
}
}
The property is marked as @readonly in its PHPDoc, which means it should only be assigned once during initialization. While PHPStan allows @readonly properties to be assigned inside the constructor of the declaring class, the assignment must be on $this -- not on another instance of the same class. Assigning a @readonly property on a different object instance violates the readonly contract because it modifies state that may have already been initialized.
Assign the @readonly property on $this inside the constructor:
<?php declare(strict_types = 1);
class Foo
{
/** @readonly */
public int $value;
- public function __construct(self $other)
+ public function __construct(int $value)
{
- $other->value = 10;
+ $this->value = $value;
}
}
Alternatively, if the property should be writable on different instances, remove the @readonly annotation:
<?php declare(strict_types = 1);
class Foo
{
- /** @readonly */
public int $value;
public function __construct(self $other)
{
$other->value = 10;
}
}