调用临时对象方法的 PHP 语法
有没有办法在临时声明的对象上调用方法,而不必强制将第一个对象分配给变量?
见下文:
class Test
{
private $i = 7;
public function get() {return $this->i;}
}
$temp = new Test();
echo $temp->get(); //ok
echo new Test()->get(); //invalid syntax
echo {new Test()}->get(); //invalid syntax
echo ${new Test()}->get(); //invalid syntax
Is there a way to call a method on a temporary declared object without being forced to assign 1st the object to a variable?
See below:
class Test
{
private $i = 7;
public function get() {return $this->i;}
}
$temp = new Test();
echo $temp->get(); //ok
echo new Test()->get(); //invalid syntax
echo {new Test()}->get(); //invalid syntax
echo ${new Test()}->get(); //invalid syntax
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
当我想要这种行为时,我使用以下解决方法。
我声明这个函数(在全局范围内):
然后我这样使用它:
I use the following workaround when I want to have this behaviour.
I declare this function (in the global scope) :
Then I use it this way :
你能做的是
What you can do is
为什么不这样做:
Why not just do this:
不幸的是,你不能这样做。恐怕 PHP 就是这样。
Unfortunately, you can't do that. It's just the way PHP is, I'm afraid.
不可以。这是 PHP 解析器的限制。
No. This is a limitation in PHP's parser.
我经常使用这个方便的小功能
用法
或
i often use this handy little function
usage
or
不可能,为什么要以这种方式创建一个对象?
对象的要点是封装唯一的状态。在您给出的示例中,
$i
将始终为 7,因此创建对象、然后从中获取$i
然后将对象丢失给对象是没有意义的。垃圾收集器,因为返回$i
后没有对该对象的引用。正如其他地方所示,静态类对于此目的更有意义。或关闭。相关主题:
Impossible and why would you create an object this way at all?
The point of an object is to encapsulate unique state. In the example you gave,
$i
will always be 7, so there is no point in creating the object, then getting$i
from it and then losing the object to the Garbage collector because there is no reference to the object after$i
was returned. A static class, like shown elsewhere, makes much more sense for this purpose. Or a closure.Related topic:
这是一个老问题:我只是提供更新的答案。
在所有受支持的 PHP 版本(自 2012 年 5.4.0 起)中,您可以执行以下操作:
请参阅 https://secure.php.net/manual/en/migration54.new-features.php(“实例化时的类成员访问”)。
This is an old question: I'm just providing an updated answer.
In all supported versions of PHP (since 5.4.0, in 2012) you can do this:
See https://secure.php.net/manual/en/migration54.new-features.php ("Class member access on instantiation").
最近在 php-internals 上出现了这个问题,不幸的是,一些有影响力的人(例如狙击手)积极参与 PHP 的开发 反对该功能。发送电子邮件至[电子邮件受保护],让他们知道您是成年程序员。
This has come up very recently on php-internals, and unfortunately some influential people (e. g. sniper) active in development of PHP oppose the feature. Drop an email to [email protected], let them know you're a grownup programmer.