1

I've tried searching for this but frankly I don't know what to search for and unfortunately I imagine this question has been asked before.

In PHP, and possibly other languages, why can't I use an object immediately after I create it?

// This causes an error
$obj = new Object()->myFunction();

Note: I return $this in most of my setter functions so I can chain them together

function myFunction() {
    // ... some more code here ...

    return $this;
}
4

3 回答 3

6

这只是 PHP 中的无效语法。您可以通过用括号包裹对象构造函数表达式来使其在 PHP 5.4 中工作:

$obj = (new Object())->myFunction();

查看PHP 5.4 新特性

  • 添加了对实例化的类成员访问,例如(new Foo)->bar().

如果你想$obj成为新对象的值,一定$this要从返回Object::myFunction()(这称为方法链)。

使构造函数链接起作用的另一种方法是在您的类中使用一个静态方法,该方法为您创建新的类实例:

class Object {
    public function __construct($var) {
        $this->var = $var;
    }
    public static function newObject($var) {
        return new Object($var);
    }
}

$obj = Object::newObject()->chainMethodX()->chainMethodY()->...
于 2013-06-11T19:38:46.117 回答
2

这是无效的语法。

PHP 仅支持:

$obj = new Object();
$obj->myFunction();

请记住,如果您的代码示例正常工作,$obj将获得myFunction().

于 2013-06-11T19:38:13.660 回答
1

虽然网站上没有记录,但它看起来好像对象运算符->的优先级高于 new 关键字。所以说:

$obj = new Object()->someFunction();

像你写的那样被评估

$obj = new (Object()->someFunction());

而不是预期的

$obj = (new Object())->someFunction();

它以这种方式工作的真正原因在于 第 775 行的 php 语法定义

于 2013-06-11T20:02:56.537 回答