Take the 2-minute tour ×

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);
// ...

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.

share|improve this question
I agree and sympathize, but what is your question? I think this can't be circumvented... –  Pekka 웃 Dec 18 '10 at 17:24
I was hoping there is a pattern how to do this without cluttering your code with a static function that basically does nothing. –  slosd Dec 18 '10 at 17:29
Not yet, maybe in PHP 5.4 :) –  StasM Dec 19 '10 at 4:31
add comment

3 Answers

up vote 2 down vote accepted

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.

share|improve this answer
add comment

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?

share|improve this answer
You are right. In fact I wouldn't actually expect this to work. That's why I added the example with correct brackets (new A('foo'))->bar() –  slosd Dec 18 '10 at 18:49
add comment

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:


share|improve this answer
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. –  Jan Dvorak Jan 27 at 16:44
I wrote my answer believing that the satisfying answer would be just to say that "now it is possible, from version x onwards", and the link was just for the reference of that. Anyway, kmas has already amended the section to the answer, but as you can see, that is only an exact copy of the question, because the question itself now is also the answer. –  Elmo Allén Mar 6 at 15:33
add comment

Your Answer


