在 PHP 中,你可以在同一行实例化一个对象并调用一个方法吗? [英] In PHP, can you instantiate an object and call a method on the same line?

查看:23
本文介绍了在 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().

这篇关于在 PHP 中,你可以在同一行实例化一个对象并调用一个方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆