简体   繁体   中英

Why can't I use an object when I construct it?

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;
}

It's simply invalid syntax in PHP. You are able to get this to work in PHP 5.4 by wrapping the object constructor expression with parentheses:

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

See PHP 5.4 new features :

  • Class member access on instantiation has been added, eg (new Foo)->bar() .

If you want $obj to be the value of the new Object, be sure to return $this from Object::myFunction() (this is called method chaining ).

An alternative for getting constructor chaining to work is to have a static method in your class which creates the new class instance for you:

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

$obj = Object::newObject()->chainMethodX()->chainMethodY()->...

This is invalid syntax.

PHP only supports:

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

Keep in mind that, were you code sample to work, $obj would get the return value of myFunction() .

Although not documented on the site it would appear as though the object operator -> has a higher precedence then the new keyword. So saying:

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

is evaluated like you wrote

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

instead of the intended

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

The real reason it works this way is in the php grammer definition on line 775

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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