4

Apologies for not being able to better articulate this issue. I've tried doing some simple testing and haven't been able to shed much light. In any case, I'm wonder what, if any, difference exists between the following two examples:

<?php
class foo
{
   public function __construct()
   {
   }
}

$foo1 = new foo;

And this:

<?php
class foo
{
   public function __construct()
   {
   }
}

$foo1 = new foo();

Note that in the second example I am using parenthesis along with the 'new' keyword. If there are not differences here, is there something I could do to my foo class declaration that would create differences? And if differences exist, are they particular to PHP? Thanks.

oliakaoil
  • 1,615
  • 2
  • 15
  • 36
  • 4
    They are essentially the same, both will call the `__construct()` method. However, if you required some parameters when instantiating the object then your parenthesis are required. – Crackertastic Oct 17 '14 at 15:47
  • thanks..the question you linked seems like a duplicate. answers my question perfectly. – oliakaoil Oct 17 '14 at 15:49
  • If your constructer takes no parameters, then call your,class without the beacess or with, whatever your preference is, if you have constructor parameters then use braces to parse the vvalues – Daryl Gill Oct 17 '14 at 16:10

1 Answers1

2

I feel that it's better to instantiate your classes using the parenthesis, even if the constructor doesn't need any arguments. While your examples do the same thing, they wouldn't if the constructor changed. It's a matter of taste and style though.

Here's your first example:

<?php
class foo
{
   public function __construct()
}

$foo1 = new foo;

That works, but what if we did this?

public function __construct($db = null) {}

.. well, then it will still work, because the arguments have default values.

But what if we did this?

public function __construct($db) {}

.. it would break due to a missing argument, and you need parenthesis in order to pass arguments. If you ever went back and made the foo constructor more interesting, you'd then just have to add the parenthesis along with all of the arguments.

Finally, languages do evolve. I don't ever see PHP complaining when you use parenthesis, but it could one day become grumpy if you don't. Some do use the no-parenthesis way to say this class we're instantiating has no constructor. It's .. personal taste. You could use the absence meaningfully:

$f = new foo; // class has no constructor, or constructor has no arguments
$f = new foo(); // class has a constructor with default arguments we can set later
$f = new foo($bar) // class has a constructor, and it needs arguments

The above can save time if done consistently throughout a large code base. I'm not sure so much any longer, as folks get better at testing - but that's only my opinion.

Currently, however - no, there's no difference between the two given your examples.

Tim Post
  • 33,371
  • 15
  • 110
  • 174