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
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With