3

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

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?

Community
  • 1
  • 1
Tom Pažourek
  • 9,582
  • 8
  • 66
  • 107
  • Have you even tried it yourself to see if it works?? – Mark Rushakoff Sep 17 '09 at 16:47
  • http://stackoverflow.com/questions/1402505/in-php-can-you-instantiate-an-object-and-call-a-method-on-the-same-line – karim79 Sep 17 '09 at 16:50
  • @Mark Rushakoff: The code new MyClass()->method() is invalid (parse error), so I would like to know if it's possible to achieve this somehow else. – Tom Pažourek Sep 17 '09 at 16:50
  • Hi, you can take a look at the answer I gave to this question : http://stackoverflow.com/questions/1402505/in-php-can-you-instantiate-an-object-and-call-a-method-on-the-same-line/1402526#1402526 – Pascal MARTIN Sep 17 '09 at 16:50
  • In spite of what is said in the other question (http://stackoverflow.com/questions/1402505/in-php-can-you-instantiate-an-object-and-call-a-method-on-the-same-line) I'm certain it is possible, but I can't find the incantation at the moment. Suffice to say it's ugly and not worth the effort. – Brenton Alker Sep 17 '09 at 16:56
  • Thanks, please close it as duplicate. I didn't see the question (probably because I searched the keyword 'instance' and the question doesn't contain it). – Tom Pažourek Sep 17 '09 at 16:56

3 Answers3

3

Previously answered:

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

Community
  • 1
  • 1
karim79
  • 339,989
  • 67
  • 413
  • 406
1

The feature you have asked for is available from PHP 5.4. Here is the list of new features in PHP 5.4:

http://docs.php.net/manual/en/migration54.new-features.php

And the relevant part from the new features list:

Class member access on instantiation has been added, e.g. (new Foo)->bar().

Delian Krustev
  • 2,826
  • 1
  • 19
  • 15
1

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
  • 11,016
  • 7
  • 41
  • 48