views:

86

answers:

2

Is it possible?

Normally, it requires two lines:

$instance = new MyClass();
$variable = $instance->method();

Is something like this possible in PHP?:

$variable = new MyClass()->method();

Of course, the first code is better for readability and clean code, etc., but I was just curious if you can shrink it. Maybe it could be useful, if the method returned another instance, e.g.:

$instance = new MyClass()->methodThatReturnsInstance();

Is it possible in PHP?

+1  A: 

You could make a static method that constructs a default instance and return it.

class Foo
{
     public static function instance() { return new Foo(); }
     ...
}

echo Foo::instance()->someMethod();

I don't really recommend this though as it's just syntactic sugar. You're only cutting out one line and losing readability.

smack0007
+2  A: 

Previously answered:

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

karim79