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 will expand your classes will omitt ocnstructor call, then you can create some variable and set it to some value in constructor. Then in working methods, you can check if this variables is still set like in constructor association. Then, if other developer will forget to call your parent constructor, this custom variable will not be set and you can throw a Exception, or other sign of error, to ensure that developer of a subclass will init object properly by parent constructor call.

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP