简体   繁体   English

使用PHP中的对象函数调用链接构造函数

[英]Chaining a constructor with an object function call in PHP

Does anyone know if the following expression will be possible in the next version(s) of PHP? 有谁知道在PHP的下一个版本中是否可以使用以下表达式?

(new A())->a();    // Causes a syntax error

I find very annoying that currently one must write 2 lines instead of 1: 我觉得非常讨厌,目前必须写2行而不是1行:

$c = new A();
$c->a();

The first version does not cause a parse error, it is perfectly valid. 第一个版本不会导致解析错误,它完全有效。 The second it is, indeed not possible, but you can easily overcome such a problem with some coding standards. 第二个,实际上是不可能的,但你可以用一些编码标准轻松克服这个问题。

If every team member creates, for each defined class, a function with the same name as the class, and a signature similar to the signature of the class constructor, then you won't have the second problem. 如果每个团队成员为每个定义的类创建一个与该类同名的函数,以及一个类似于类构造函数签名的签名,那么您将不会遇到第二个问题。 Example: 例:

class Foo
{
    public function __construct($param)
    {}

    public function bar()
    {}
}

/**
 * @return Foo
 */
function Foo($param)
{
    return new Foo($param);
}

Foo()->bar();

Of course, you'll still have problems with library code. 当然,您仍然会遇到库代码问题。

A new-expression can be used as a function argument. new-expression可以用作函数参数。 A function call can be used as the left-hand side of the member access operator. 函数调用可以用作成员访问运算符的左侧。 Therefore, you just need to define a single function: 因此,您只需要定义一个函数:

function with($object) { return $object; }

with(new A()) -> a();

No additional efforts required on a per-class basis. 每班不需要额外的努力。

This is possible as of PHP 5.4+ : 这可以从PHP 5.4+开始

Class member access on instantiation has been added, eg (new Foo)->bar(). 已添加实例化的类成员访问权限,例如(new Foo) - > bar()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM