Skip parenthesis when chaining methods or properties in PHP 8.4

Video Lesson: Skip parenthesis when chaining methods or properties in PHP 8.4

Lesson Content

PHP 8.4 introduces a cleaner syntax when you need to chain on methods after directly instantiating an object.

Now you can complete skip typing those extra parentheses that were previously required.

Before PHP 8.4, you’d need to wrap new objects in parentheses if you wanted to immediately call a method on it:

$greeting = (new MyClass())->greet();

But with PHP 8.4, you can now directly chain methods without adding in the parentheses:

$greeting = new MyClass()->greet();

One small but important thing to note though is that you must include the parentheses when using this syntax, even if it’s constructor is empty:

// Won't work with method chaining
$greeting = new MyClass->greet();  // Error!

// This works
$greeting = new MyClass()->greet();

This also works when accessing properties:

// Property access also works!
new MyClass()->message;

If you have dynamic class names, or anonymous classes, it also works:

// Dynamic class names
$myClass = 'MyClass';
new $myClass()->greet();

// Anonymous classes
new class {
    public string $message = "Hello, World!";

    public function __construct() {
        echo "MyClass instance created!";
    }

    public function greet(): string {
        return "Hey there!";
    }
}->greet();

This small syntax improvement removes a common friction point in PHP code, and makes it more natural to immediately chain on a method after creating an object.