Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 438
Marco Demaio Avatar asked Nov 27 '22 12:11

Marco Demaio


2 Answers

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();
like image 178
ratibus Avatar answered Dec 03 '22 10:12

ratibus


What you can do is

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

   public static function getNew() { return new self(); }
}

echo Test::getNew()->get();
like image 37
Michael Krelin - hacker Avatar answered Dec 03 '22 12:12

Michael Krelin - hacker