phpchaining

Why are parentheses needed in constructor 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();

Solution

  • 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.