Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP empty constructor

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

like image 825
Mark Blades Avatar asked Oct 06 '11 10:10

Mark Blades


People also ask

Is Empty constructor needed?

Answer: C++ Empty constructor necessity depends upon class design requirements. We know that C++ class constructor is called when we create an object of a class. If a class is not required to initialize its data member or does not contain data member, there is no need to write empty constructor explicitly.

Can a class have an empty constructor?

Having an empty constructor (whether static or not) in a class is redundant, and ReSharper issues a warning to that effect. In the above, an empty static constructor is, in fact, a necessary detail that guarantees lazy initialization.

What is __ construct in PHP?

PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!

Does PHP have a default constructor?

Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically. Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members. Copy Constructor: It accepts the address of the other objects as a parameter.


3 Answers

If you don't need a constructor it's best to leave it out, no need to write more code. When you DO write it, leave it empty... returning true doesn't have a purpose.

like image 92
JNDPNT Avatar answered Oct 12 '22 05:10

JNDPNT


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

So if you don't need it and you do not want to overwrite the parent constructor explicitly, don't write it at all.

like image 24
hakre Avatar answered Oct 12 '22 04:10

hakre


You should only define an empty constructor if your object should never be instantiated. If that is the case, make the __construct() private.

like image 31
alex Avatar answered Oct 12 '22 04:10

alex