Search code examples
phpobjectooptemporary

PHP syntax to call methods on temporary objects


Is there a way to call a method on a temporary declared object without being forced to assign 1st the object to a variable?

See below:

class Test
{
   private $i = 7;      
   public function get() {return $this->i;}   
}

$temp = new Test();
echo $temp->get(); //ok

echo new Test()->get(); //invalid syntax
echo {new Test()}->get(); //invalid syntax
echo ${new Test()}->get(); //invalid syntax

Solution

  • I use the following workaround when I want to have this behaviour.

    I declare this function (in the global scope) :

    function take($that) { return $that; }
    

    Then I use it this way :

    echo take(new Test())->get();