在 PHP 中,你可以在同一行实例化一个对象并调用一个方法吗?
问题描述:
我想做的是这样的:
$method_result = new Obj()->method();
而不必这样做:
$obj = new Obj();
$method_result = $obj->method();
在我的具体情况下,结果对我来说实际上并不重要.但是,有没有办法做到这一点?
The result doesn't actually matter to me in my specific case. But, is there a way to do this?
答
您要求的功能可从 PHP 5.4 获得.以下是 PHP 5.4 中的新功能列表:
The feature you have asked for is available from PHP 5.4. Here is the list of new features in PHP 5.4:
http://php.net/manual/en/migration54.new-功能.php
以及新功能列表中的相关部分:
And the relevant part from the new features list:
添加了实例化时的类成员访问权限,例如(new Foo)->bar().
Class member access on instantiation has been added, e.g. (new Foo)->bar().