Cannot combine nullsafe operator with Closure creation
Description
PHP 8.1 introduced the first class callable syntax, using (...) to create a Closure from a method or function call, without invoking it.
The nullsafe operator ?-> short-circuits the call when the object is null, evaluating to null instead. Combined with Closure creation, this would mean the expression sometimes returns a Closure and sometimes null, which is not a coherent result for the engine to compile.
This combination is therefore forbidden, and detected at compile time.
Example
<?php
class X {
public function foo() {}
}
$x = new X();
$closure = $x?->foo(...);
?>
Alternatives
- Use the
->operator instead of?->, making sure the object is nevernullat that point. - Check the object for
nullexplicitly, before creating the Closure.
Related error messages
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See