PHP may introduce “new” in initializers in the next release

336 0

The last major release of PHP, 8.0, which was made available last November, brought many improvements to the language, one of which was Constructor Property Promotion by Nikita Popov. Now, Nikita proposes one new RFC, which will allow us to use the new  keyword within the constructor properties initializers.

What is Constructor Property Promotion?

Basically, without constructor property promotion, you would need to define a lot of boilerplate to initialize the properties of a given class:

class Point {
    public float $x;
    public float $y;
    public float $z;
 
    public function __construct(
        float $x = 0.0,
        float $y = 0.0,
        float $z = 0.0,
    ) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }
}

With the approval of the Constructor Property Promotion RFC, the class above can be simplified by initializing all the properties during constructor declaration:

class Point {
class Point {
    public function __construct(
        public float $x = 0.0,
        public float $y = 0.0,
        public float $z = 0.0,
    ) {}
}

Using new initializer on constructor

Now, if the new RFC passes, we will be able to initialize objects on the constructor parameters too. new expressions are allowed as part of initializer expressions. It will be possible to pass arguments to the constructor, including the use of named arguments:

function test(
    $foo = new A,
    $bar = new B(1),
    $baz = new C(x: 2),
) {
}

This will, of course simplify our codebase even more, specially if we are already taking advantage of other recent syntactic sugar improvements that were introduced on the recent releases of the language:

  • Arrow functions
  • Null coalescing
  • Numeric value formatting
  • Spread operator in arrays
  • Null-safe operator
  • Named arguments

The RFC is currently under discussion.

Let me know what do you think about this proposal.

(Visited 87 times, 1 visits today)

Elisio Leonardo

Elisio Leonardo is an experienced Web Developer, Solutions Architect, Digital Marketing Expert, and content producer with a passion for technology, artificial intelligence, web development, and entertainment. With nearly 15 years of writing engaging content on technology and entertainment, particularly Comic Book Movies, Elisio has become a trusted source of information in the digital landscape.