PHP empty constructor

Just wondering, is it better to define an empty constructor or leave the constructor definition completely in PHP? I have the habit of defining constructors with just return true; , even if I don’t need a constructor to do something - only for reasons of completion.

+8
constructor php
source share
5 answers

If you do not need a constructor, it is better to leave it, you do not need to write more code. When you do, leave it blank ... returning the truth has no purpose.

+10
source share

EDIT:

the previous answer is no longer valid, since now PHP behaves like other oop programming languages. constructors are not part of interfaces. so now you can redefine them as you prefer, without any problems.

the only exception is the following:

 interface iTest { function __construct(A $a, B $b, Array $c); } class Test implements iTest { function __construct(A $a, B $b, Array $c){} // in this case the constructor must be compatible with the one specified in the interface // this is something that php allows but that should never be used // in fact as i stated earlier, constructors must not be part of interfaces } 

PREVIOUS OLD NON-VALID RESPONSE:

there is a significant difference between an empty constructor and no constructor at all

 class A{} class B extends A{ function __construct(ArrayObject $a, DOMDocument $b){} } VS class A{ function __construct(){} } class B extends A{ function __construct(ArrayObject $a, DOMDocument $b){} } // error B::__construct should be compatible with A constructor 
+5
source share

There is a difference between the two: if you write an empty __construct() function, you overwrite any inherited __construct() from the parent class.

So, if you do not need this, and you do not want to explicitly rewrite the parent constructor, do not write it at all.

+3
source share

You must define an empty constructor if your object should never be created. If so, make __construct() private.

+2
source share
Constructor

always returns an instance of the class in which it is defined. Therefore, you never use "return" inside the constructor. Finally, it is best not to define it if you are not using it.

+1
source share

All Articles