Is it possible to create an instance and call method in one command (on one line) in PHP?

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

Is it possible?

This usually requires two lines:

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

There is something similar 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 could compress it. Maybe this can be useful if the method returns another instance, for example:

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

Is this possible in PHP?

+3
source share
3 answers

, .

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

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

, . .

+1

The requested function is available in PHP 5.4. Here is a list of new features in PHP 5.4:

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

And the corresponding part from the list of new functions:

Added access to a class member when creating an instance, for example. (new Foo) → bar ().

+1
source

Source: https://habr.com/ru/post/1717946/


All Articles