Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 never null at that point.
  • Check the object for null explicitly, before creating the Closure.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See