In PHP, can you instantiate an object and call a method on the same line?

Viewed 66805

What I would like to do is something like this:

$method_result = new Obj()->method();

Instead of having to do:

$obj = new Obj();
$method_result = $obj->method();

The result doesn't actually matter to me in my specific case. But, is there a way to do this?

9 Answers

Simply we can do this

$method_result = (new Obj())->method();
Related