Constructor In PHP
In this article I expalin PHP cnstructor.
Constructor
The constructor is an "OOP" feature. PHP 5 has OOP capability and gives the authority to developers to declare a constructor method for classes. I will first explain what a constructor is. The answer is "A constructor is a special type of method that is automatically called when you create a new instance of the class". The OOP constructor has a number of advantages, they are:
- Constructors can accept parameters, that are assigned to specific object fields at creation time.
- Constructors can call class methods or other functions.
- Class constructors can call on other constructors, including those from the parent class.
Example
<?php
class Myclass
{
function __construct()
{
print "Parent class constructor.</br>";
}
}
class Baseclass extends Myclass
{
function __construct()
{
parent::__construct();
print " Child Class constructor\n";
}
}
$obj = new Myclass();
$obj = new Baseclass();
?>
Output