编程

PHP 8.4 中是否实现不带额外括号的类实例化?

185 2024-05-28 12:00:00

略去 new 表达式周围括号的 RFC 可能会出现在 PHP 8.4 中。该 RFC 目前处于投票阶段,有 21 张“赞成”票和 3 张“反对”票。投票将于 5 月 24 日结束,因此 ⅔ 的投票仍有可能失败,但乐观地说,看起来它正朝着正确的方向前进。
自从引入了实例化期间的成员访问,你必须将 new MyClass() 调用封装在括号中,否则将出现解析错误。此建议的语法将允许无需额外的括号访问常量、属性和方法:

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');

此处是一些通过该特性你可以使用的一些通用例子:

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"
);

你可以在 RFC 中阅读有关此提案的所有详细信息。此功能可能会在 PHP 8.4 中落地。