Error Identifier: nullsafe.assign
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 doFoo(?\stdClass $a): void
{
$a?->foo = 'bar'; // ERROR: Nullsafe operator cannot be on left side of assignment.
}
}
Why is it reported? #
PHP does not allow the nullsafe operator (?->) on the left side of an assignment. The nullsafe operator is designed for reading values and short-circuiting to null when the object is null. Assigning a value through the nullsafe operator is a syntax error in PHP because the semantics of what should happen when the object is null during assignment are undefined.
This is a language-level restriction that cannot be worked around.
How to fix it #
Use a regular null check before the assignment:
<?php declare(strict_types = 1);
class Foo
{
public function doFoo(?\stdClass $a): void
{
- $a?->foo = 'bar';
+ if ($a !== null) {
+ $a->foo = 'bar';
+ }
}
}
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Operators\InvalidAssignVarRule [1]