-1

I have a PHP class with a member returning an assoative array. I may do

$bar = new foo();
$something = $bar->zork();

and $Something contains what I expect.

If I do

$something = new foo()->zork();

I get an error: unexpected T_OBJECT_OPERATOR.

Can this construction, that is very common in Java, be done in PHP?

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • See http://stackoverflow.com/questions/2188629/php-how-to-chain-method-on-a-newly-created-object?rq=1 (however the accepted answer does not cover the syntax noted by Mark Baker and [here](http://stackoverflow.com/a/16296437/2864740), which is PHP 5.4+) – user2864740 Jun 18 '14 at 23:57
  • http://stackoverflow.com/questions/18873341/call-function-directly-after-constructor-new-object-callfunction?rq=1 – user2864740 Jun 18 '14 at 23:58

1 Answers1

2

It is allowed, but use

$something = (new foo())->zork();

The extra brackets are essential

And I believe this syntax was only introduced in PHP 5.4.0, so you'd still get an error with earlier versions of PHP

Mark Baker
  • 209,507
  • 32
  • 346
  • 385