Is class instantiation without extra parenthesis coming to PHP 8.4?
Published on by Paul Redmond
The RFC for omitting parentheses around the new
expression is likely coming to PHP 8.4. This RFC is currently in the voting phase, with 21 "yes" and 3 "no" votes. Voting ends May 24th, so there's still a chance the 2/3 vote could fail, but optimistically, it looks like it's heading in the right direction.
Since member access during instantiation was introduced, you must wrap the new MyClass()
call in parentheses, or you'll get a parse error. The proposed syntax would allow you to access constants, properties, and methods without the extra parentheses:
class Request implements Psr\Http\Message\RequestInterface{ // ...} // Valid$request = (new Request())->withMethod('GET')->withUri('/hello-world'); // PHP Parse error: syntax error, unexpected token "->"$request = new Request()->withMethod('GET')->withUri('/hello-world');
Here are some common examples you'll probably use with this feature (the RFC has more examples):
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");
You can read all the details about this proposed change in the RFC. This feature likely drops in PHP 8.4. The implementation looks to be code-complete (not approved and merged yet) and can be found on GitHub.