Posts

Showing posts with the label constructor

Call parent constructor in PHP

You can call constructor of the superclass of your class. Why to do that? It's important if you write your own constructor. If you derive from a class and write custom constructor then, when object is creating o only yours constructor will be called. This can casue a situation, when object isn't propably initialised. For example, some fields can be not set, null valued etc. To prevent those situations it is a good practice to call parent construtor in your class constructor as the first line like example below: public function __construct() { parent::__construct( 11 ); } In this situation you prevents errors like uninitialised class variables, uncalled other initialisation methods etc. As you can see, there is also a posibility to pass some variables to parent conscturctor. This is common case - if you derive from a class, wich have some variables in constructor, then you have to pass those variables in parent constructor call. If you are afraid, that some developer who wil...

How to call parent constructor ?

If you write your own constructor, you propably will want to call a parent construtor first to set up a class. You can do it in that way: parent::__construct(); This can be used also to call parent methods.