【问题标题】:Is it possible to create instance and call method in one command (on the same line) in PHP? [duplicate]是否可以在 PHP 中的一个命令(在同一行)中创建实例和调用方法? [复制]
【发布时间】:2010-11-29 05:26:38
【问题描述】:

可能重复:
In PHP, can you instantiate an object and call a method on the same line?

有可能吗?

通常需要两行:

$instance = new MyClass();
$variable = $instance->method();

在 PHP 中可以实现这样的事情吗?:

$variable = new MyClass()->method();

当然,第一个代码在可读性和代码简洁等方面更好,但我只是好奇你是否可以缩小它。如果方法返回另一个实例,也许它会很有用,例如:

$instance = new MyClass()->methodThatReturnsInstance();

在 PHP 中可以吗?

【问题讨论】:

标签: php object methods instance


【解决方案1】:
【解决方案2】:

您可以创建一个构造默认实例并返回它的静态方法。

class Foo
{
     public static function instance() { return new Foo(); }
     ...
}

echo Foo::instance()->someMethod();

我并不真正推荐这个,因为它只是语法糖。你只是删掉了一行并且失去了可读性。

【讨论】:

    【解决方案3】:

    您要求的功能可从 PHP 5.4 获得。以下是 PHP 5.4 的新特性列表:

    http://docs.php.net/manual/en/migration54.new-features.php

    以及新功能列表中的相关部分:

    已添加实例化时的类成员访问权限,例如(new Foo)->bar().

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 2019-11-13
      • 2011-12-18
      相关资源
      最近更新 更多