简体   繁体   中英

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.

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, eg (new Foo)->bar().

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM