76

I've always assumed that - in the absence of constructor parameters - the parentheses (curly brackets) follow the class name when creating a class instance, were optional, and that you could include or exclude them at your own personal whim.

That these two statements were equal:

$foo = new bar;
$foo = new bar();

Am I right? Or is there some significance to the brackets that I am unaware of?

I know this sounds like a RTM question, but I've been searching for a while (including the entire PHP OOP section) and I can't seem to find a straight answer.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Atli
  • 7,855
  • 2
  • 30
  • 43
  • I know this would be an old answer, but based on **PSR12** coding style: https://www.php-fig.org/psr/psr-12/, **"When instantiating a new class, parentheses MUST always be present even when there are no arguments passed to the constructor."** – Blues Clues Sep 12 '21 at 08:10

2 Answers2

60

They are equivalent. If you are not coding by any code convention, use which you like better. Personally, I like to leave it out, as it is really just clutter to me.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 2
    Agreed. If the constructor doesn't take any parameters I leave them out too – AntonioCS Dec 22 '09 at 12:21
  • 1
    Thanks. I was hoping this was the case. - Personally I like to always include them. Bad habit from my Java/C# days :) – Atli Dec 22 '09 at 12:24
  • 22
    ..also, the end part looks like a smirking singing monkey (); laaaa-la – 0scar Dec 22 '09 at 13:08
  • 5
    I'd still argue that it's more conventional to keep the parenthesis! (: friendlier to non-C/C++ background friends coming from C# or Java. – mauris Feb 17 '12 at 09:51
  • 6
    I would not leave them out since it is still a *function call* - a call to the constructor method.It is also not allowed to omit the `()` when you call other functions or methods which takes no required parameters. So why should I do this with constructor? `new Foo()` instead of `new Foo` is better for readability IMHO. – hek2mgl Jul 19 '15 at 22:51
  • You can enforce using `new` with braces using https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/2.3/src/Fixer/Operator/NewWithBracesFixer.php. – localheinz Jul 01 '17 at 08:41
  • It's not really a function call - the constructor, if it exists, is called automatically by the system, but not directly. The return value from new is the new instance, it isn't anything returned from the constructor. – bdsl Mar 03 '21 at 18:19
6

$foo = new bar() would be useful over $foo = new bar if you were passing arguments to the constructor. For example:

class bar {

    public $user_id;

    function __construct( $user_id ) {
        $this->user_id = $user_id
    }
}

-

$foo = new bar( $user_id );

Aside from that, and as already mentioned in the accepted answer, there is no difference.

henrywright
  • 10,070
  • 23
  • 89
  • 150