DrewT DrewT - 6 months ago 40
PHP Question

Syntax for new class declarations in PHP

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

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
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
instead of
. Is that correct?



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.