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:
<?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