Use new Keyword Without Parentheses in PHP 8.4

Use new Keyword Without Parentheses in PHP 8.4

The new keyword enables the creation of a class instance. Since PHP 8.4, enclosing the new keyword in parentheses is no longer required to chain method calls, access properties, and more.

Let's say we have the following class:

Dog.php

<?php

class Dog
{
    public function makeSound(): void
    {
        echo 'Woof';
    }
}

Before PHP 8.4, constants, properties, and methods could be accessed directly on a newly created instance without using an intermediate variable, but only when the new keyword was enclosed in parentheses.

<?php

require_once 'Dog.php';

(new Dog())->makeSound();

Since PHP 8.4, constants, properties, and methods of a newly instantiated object can be accessed directly without wrapping the new keyword in parentheses.

<?php

require_once 'Dog.php';

new Dog()->makeSound();

This change streamlines code, making it cleaner and more readable.

Leave a Comment

Cancel reply

Your email address will not be published.