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.
PHP Coding tips & tricks. Function & error explanation, coding style, how tos etc. Short notes posted directly from developer work environment.
PHP Coding Tips
Tuesday, March 19, 2013
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:
Subscribe to:
Post Comments (Atom)
have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletePHP 7 Training in chennai | PHP 7 Training Course
PHP 7 Training in chennai | Online PHP 7 Course