Background
[wp_ad_camp_3]
This article demonstrates how constructors work in PHP. It will also touch on destructors just briefly. If you’re a Java programmer who has somehow become bored with anything Java and wanted to explore PHP, the first thing you need to realize is OOP in PHP is slightly different. Take for instance, constructors.
The constructors in PHP work differently to that of Java’s.
Software Requirements
- Windows 7 Professional SP1
- PHP 5.5.9 / Zend Engine v2.5.0
- NetBeans IDE 8.0.1
Constructor Definition
In PHP 5+, constructors are defined using the keyword __construct as a method name. This is the recommended way of definining constructors.
[wp_ad_camp_4]
1 2 3 | class Animal { public function __constructor() {} } |
Also note that you cannot overload any functions in PHP. That includes methods like constructors.
1 2 3 4 5 | // Class definition is invalid because of __contructor keyword has been used more than once as a method name class Animal { public function __constructor() {} public function __constructor($name, $description) {} } |
Inheriting and Overriding Constructors
In a parent-child classes, when a subclass has its own constructor and is instantiated, the parent constructor is never invoked. There are two ways to have the parent constructor executed:
1. Explicitly call the parent contructor from the subclass’ constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Animal { public function __construct() { // Animal codes here } } class Dog extends Animal { public function __construct() { parent::__construct(); // Dog-specific codes hereafter } } |
2. Do not override the constructor in the subclass
This effectively executes the parent constructor.
Destructor
If you are familiar with Object.finalize() in Java or methods annotated with @PreDestroy, the equivalent of that in PHP is the destructor method. Destructors are defined using the __destruct keyword.
[wp_ad_camp_5]
1 2 3 4 5 | class Dog extends Animal { public function __destruct() { } } |