1

I inherited a php project that was previously assigned to another development company and I often see very strange code implementations which I've never seen before and which I think are probably errors. That said, they are everywhere and the server logs don't complain about them or cast warnings. It's possible that error_reporting has been turned off somewhere.

For example, I am seeing a lot of class declarations like this:

$registration = new EventRegistration;

That's strange to me, as I've only ever seen class instancing using new done as:

$registration = new EventRegistration();

Can someone clarify if this is incorrect / not best practice / passable?

I assume it's just a syntax error that will compile but is technically wrong. Something similar to when people do array syntax like $array[key] instead of $array['key']. Is that correct?

Thanks.

DrewT
  • 4,983
  • 2
  • 40
  • 53
  • 2
    No it isn't an error or warning or technically wrong, braces are only necessary if there are any arguments that need passing to the class constructor – Mark Baker Nov 16 '16 at 22:53
  • Okay thanks, I do see why it wouldn't be needed without any constructor args. – DrewT Nov 16 '16 at 23:05

1 Answers1

1

With the new keyword you want to create a new object, if that object does not require any arguments (as defined in the __construct() method) its perfectly fine do leave out the ().

class foo{
    function __construct(){}
} // valid

class bar{
    function __construct($arg = null){}
} // valid

class foobar{
    function __construct($arg){}
} // not valid

In this scenario, only foobar will trigger a warning if you do not pass any args. Its a matter of preference I would say.

But for $array[key] would say key is a constant and would likely trigger a warning.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
  • Yes that's true although `$array[key]` will compile it does cast a warning with error reporting turned on. It's not good syntax but I've seen it elsewhere in the project. Thanks for the constructor examples, I understand what's up now. – DrewT Nov 16 '16 at 23:07
  • Because PHP can assume (read the warning), doesn't mean its right. – Xorifelse Nov 16 '16 at 23:39
  • Yeah, I know it's incorrect though passes that's why I wanted to check on the class declarations also. There's a lot that needs to be changed in this project xD – DrewT Nov 16 '16 at 23:58