Calling class methods without parentheses in PHP 8.4

Marcos Marcolin • May 15, 2024 • 2 min read

php php84 phprfc opensource

Omitting parentheses when calling class methods

With PHP 8.4, you'll be able to call class methods without using parentheses when creating the instance. 🐘

That's what the RFC proposes: new MyClass()->method() without parentheses.

Starting with PHP 5.4.0, the "class member access on instantiation" feature was introduced.

That means, since that version, it's been possible to access constants, properties, and methods of a freshly created instance without needing an intermediate variable. However, that only works if the new expression is wrapped in parentheses.

With the new RFC, it will be allowed to omit the parentheses around the new expression whenever there are parentheses for the constructor arguments, as shown in this post's image.

RFC new without parentheses

So, you'll also be able to write:

class MyClass
{
    const CONSTANT = 'constant';
    public static $staticProperty = 'staticProperty';
    public static function staticMethod(): string { return 'staticMethod'; }
    public $property = 'property';
    public function method(): string { return 'method'; }
    public function __invoke(): string { return '__invoke'; }
}

var_dump(
    new MyClass()::CONSTANT, // string(8) "constant"
    new MyClass()::$staticProperty, // string(14) "staticProperty"
    new MyClass()::staticMethod(), // string(12) "staticMethod"
    new MyClass()->property,// string(8) "property"
    new MyClass()->method(), // string(6) "method"
    new MyClass()(), // string(8) "__invoke"
);

// Before
(new MyClass())::CONSTANT;

// After
new MyClass()::CONSTANT;

So, did you like this new feature? Personally, PHP 8.4 will bring excellent additions, and this is one of the less significant improvements. Right now, I still prefer using parentheses, since it seems to make what's happening clearer, but I believe I'll get used to it easily.

It's worth remembering that this doesn't affect the use of parentheses, which will keep working as usual.

You can read more about the proposal in the official post: click here.

See you next time, and cheers! 🐘

Share: