Menu

← Back to nullsafe.*

Error Identifier: nullsafe.byRef

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 string $value = 'hello';
}

function doFoo(?Foo $foo): void
{
	$ref =& $foo?->value;
}

Why is it reported? #

The nullsafe operator (?->) cannot be used in a context that requires a reference. The nullsafe operator may return null when the left side is null, and null is not a variable that can be referenced. This applies to assignment by reference (=&), return by reference, and arrow function return by reference.

How to fix it #

Check for null explicitly instead of using the nullsafe operator:

 <?php declare(strict_types = 1);
 
 function doFoo(?Foo $foo): void
 {
-	$ref =& $foo?->value;
+	if ($foo !== null) {
+		$ref =& $foo->value;
+	}
 }

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\Functions\ArrowFunctionReturnNullsafeByRefRule [1]
  • PHPStan\Rules\Functions\ReturnNullsafeByRefRule [1]
  • PHPStan\Rules\Operators\InvalidAssignVarRule [1]

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.