-1

The following PHP code is valid:

$a = new MyClass();
$a->myFunction();

Is there a valid way to combine these two statements? My first attempt understandably results in a syntax error:

new MyClass()->myFunction();

I then added brackets around the created object, and that ran fine on PHP 5.4.17 but not on PHP 5.3.26:

(new MyClass())->myFunction();

At what point is this syntax accepted, or should I abandon this idea and just use two lines. My actual use case is more complicated and it would make the code much neater if I didn't have to keep creating single-use variables all the time.

I am unable to find anything about this in the documentation.

DanielGibbs
  • 9,910
  • 11
  • 76
  • 121

4 Answers4

1
(new MyClass())->myFunction();

is justfine since PHP 5.4. You can use it, but i think two-line approach is cleaner, backwards compatible with older PHP versions and won't confuse newcomming programmers who read your code :)

Igor Pantović
  • 9,107
  • 2
  • 30
  • 43
1

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

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

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

This answer comes directly from this question also asked here on SO.

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().

Community
  • 1
  • 1
Kyle
  • 4,421
  • 22
  • 32
1

The (new MyClass())->myFunction() notation is introduced in PHP 5.4 (including some other short-hand notations, see the new features-page).

One workaround (which I don't recommend to misuse this in all situations) is to have a static method in MyClass:

class MyClass {
    public static newInstance() {
        return new self();
    }
    public function myFunction() {}
}

MyClass::newInstance()->myFunction();
Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29