93

Possible Duplicate:
PHP class instantiation. To use or not to use the parentheses?

I have not found any official documentation on this. But afaik it doesn't matter whether a class is instantiated with our without the parentheses - as long as there are no parameters involved, right?

$car = new Car;

or

$car = new Car();

But can anyone tell me if there's a difference in performance? Which way is the 'more correct' way? Is there any official documentation for this?

Community
  • 1
  • 1
Frank
  • 933
  • 1
  • 6
  • 4

3 Answers3

138

Any difference in performance is going to be absolutely negligible.

While both ways are fine, I personally would prefer using new Car(); because usually, a method is being called here, and function/method calls in PHP require (). Also, it's more consistent with instantiations that have parameters.

But in the end, it's down to taste. It doesn't matter which way you choose, but when you choose one, stick to it consistently!

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 9
    +1 Honestly I don't consider `new ClassUsingDefaultConstructor;` and `new ClassWithConstructorWithParameters($foo, $bar);` used in the same script to be consistent *no matter what*. But that's just me I guess. – BoltClock Oct 06 '10 at 13:54
  • 3
    I always leave out the brackets if there is no arguments. Don't need the clutter and I think it looks prettier too. – Gordon Oct 06 '10 at 14:06
  • 6
    @Gordon ... seems like bad practice to use different construct approaches. Although I agree that there is an important value to creating code that is easy as possible to read ... but I think that that should come AFTER consistency. – dsdsdsdsd Jan 22 '13 at 11:44
  • 4
    @dsdsdsdsd I consistently leave out brackets when there is no arguments to the ctor – Gordon Jan 22 '13 at 12:09
  • The only place I find it cleaner is when chaining methods after constructor. `(new DateTime)->getTimezone()` looks cleaner than `(new DateTime())->getTimezone()`. – Stancell Jul 08 '21 at 05:36
  • 3
    The PSR-12 specification released in 2019 says that **“parentheses MUST always be present even when there are no arguments passed to the constructor”**. – mr_mmmmore Oct 12 '21 at 06:38
12

the first instantiation has no "official" reference. In the official php doc you alway find the second one. So, i'de prefere this for consistenscy. But it's all your choice

ArtoAle
  • 2,939
  • 1
  • 25
  • 48
  • 9
    In a quick look-through I found a great number of instances where the documentation examples use the non-parenthesized form, including many in the "Classes and Objects" section. – GZipp Oct 06 '10 at 17:07
3

They're both correct ways, and I'm sure there isn't any difference in performance either.

reko_t
  • 55,302
  • 10
  • 87
  • 77