New in initializers

Nikita Popov have just written an RFC proposal to introduce New in initializers in PHP 8.1. The RFC proposes to allow use of new expressions inside initializer expressions, including for property and parameter default values. Actually it’s not possible to write something like this :

class Test {
    public function __construct(
        private Logger $logger = new NullLogger,
    ) {}
}

Instead, it is necessary to write code along the following lines:.

class Test {
    private Logger $logger;
 
    public function __construct(
        ?Logger $logger = null,
    ) {
        $this->logger = $logger ?? new NullLogger;
    }
}

The new proposal will accept new expressions as part of initializer expressions. It is possible to pass arguments to the constructor, including the use of named arguments. However there are some exceptions that should create compile time error such as : the use of a dynamic or non-string class name, the use of argument unpacking, and the use of unsupported expressions as arguments.

New in initializers in internals

In the PHP internals Nikita indicated that “The RFC is narrow in scope in that it only adds support for “new”. An extension to other call kinds should be straightforward though.”.

Benjamin Eberlei find it the missing puzzle piece needed for nested attributes !

Check out the new RFC proposal on “New in initializers” at https://wiki.php.net/rfc/new_in_initializers

LEAVE A REPLY

Please enter your comment!
Please enter your name here