Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are parentheses needed in constructor chaining?

Tags:

php

chaining

Why do expressions that use the new keyword need parentheses in order to be utilized in chained execution? In AS3, for example, you don't need parentheses. In PHP is this a stylistic aid for the interpreter or is there a bigger reason that I'm not aware of? Is it an order of execution precedence issue?

Constructor chaining in PHP

Thanks to this question Chaining a constructor with an object function call in PHP I figured out the how…

The object definition

Aside: Apparently the magic method __construct always implicitly returns $this and if you explicitly return $this (or anything for that matter) no errors/warnings/exceptions will occur.

class Chihuahua
{
    private $food;

    function __construct( $food )
    {
        $this->food = $food;
    }

    function burp()
    {
        echo "$this->food burp!";
    }
}

Works

(new Chihuahua('cake'))->burp();

Does Not Work (but I wish it did)

new Chihuahua('cake')->burp();
like image 404
Mark Fox Avatar asked Dec 29 '12 00:12

Mark Fox


2 Answers

I believe it is because the interpreter parses into this,

new (Chihuahua('cake')->burp());

instead of,

(new Chihuahua('cake'))->burp();

since -> has a higher preference than the new operator.

And giving you an error because this,

Chihuahua('cake')->burp()

is not understood. Hope it helps.

like image 90
rae1 Avatar answered Nov 02 '22 23:11

rae1


Because the new operator has a lesser priority than the -> operator. Php try to run Chihuahua('cake')->burp() before new Chihuahua('cake'). That is the problem.

like image 33
Thomas Ruiz Avatar answered Nov 02 '22 22:11

Thomas Ruiz