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

Closure On Constructor

<?php

class x {
    public $p = 3;
    
    function __construct() {
        $this->p = 4;    
    }
}

//Cannot create Closure for new expression
//$c = new X(...);

$x = new x();
echo $x->p;
$x->p = 5;
echo $x->p;
$f = $x->__construct(...);

$f();
echo $x->p;

PHP 8.1 introduced first class callable, a syntax to build a closure by using the ellipsis operator ... as argument. This works on all sorts of calls, methods, closure, functions.

The only call where it doesn’t work is the instantiation: PHP generates an error from that syntax.

On the other hand, it is possible to create a closure on the constructor method, like any other method. And there, it just calls again the constructor, on the object that was already created.

See Also

PHP Error Messages

PHP Features

Last updated: 10 September 2026