slosd
slosd

Reputation: 3474

Use object operator right after object instantiation in PHP

It's really annoying that you can't do any of these things (and it doesn't make any sense that you can't):

new A('foo')->bar();

(new A('foo'))->bar();

The only thing I could think of is to have a static function to return a new object

public static function get($a) {
  return new self($a);
}
// ...
A::get('foo')->bar();

But that's just ugly. The reason why I need this is because in the context of the object definition I mostly pass the new object as parameter or as part of an array:

new B(array(
   new A('foo')->bar()
   new A('smt')->bar()->more()
));

bar() and more() of course return a reference to the object.

Upvotes: 2

Views: 260

Answers (3)

Elmo Allén
Elmo Allén

Reputation: 179

In PHP 5.4 this has now been made possible and thus requires no workarounds: http://www.php.net/manual/en/migration54.new-features.php

PHP 5.4.0 offers a wide range of new features:

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

Upvotes: 2

salathe
salathe

Reputation: 51950

This isn't an answer to "how to do this without cluttering your code…" but hopefully shows some light at the end of the tunnel.

There has been a recent RFC on this particular topic (see also the related developer discussion) and while there are a few points to iron out, the response was very favourable.

In the mean time, you will have to stick with your factories whether you like them or not.

Upvotes: 2

Pekka
Pekka

Reputation: 449485

No, as far as I know, using a function like you show is the only way around this.

I'm no Guru in PHP's internal workings, but the architectonical reason for this is probably that new is a language construct, and can accept different kinds of expressions. Therefore,

 new A('foo')->bar()

would be ambigous: Is the new object intended to be of the class A, or does the class name come from bar()'s return value?

Upvotes: 1

Related Questions