In this tutorial, we will learn about PHP Constructor. The constructor is a special member function in class and the main motive to create the constructor in class is to initialise the properties of every object instance of the class. An amazing thing about the constructor is, the constructor is automatically called on each newly-created object.
Please Note, that the construct function starts with two underscores (__).
Here you can check an example program to understand how to create a constructor in PHP:
<?php
class Example{
//defining constructor
function __construct() {
echo "This is Constructor in Example Class";
}
}
$obj= new Example();
?>
Types of Constructor:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
Default Constructor:
A constructor without parameters is known as the default constructor. Although we can initialise properties of the class from the default constructor and we can also call other member functions of the class from the default constructor.
<?php
class Example{
//defining constructor
function __construct() {
$this->sayHello();
echo "This is Constructor in Example Class";
}
function sayHello() {
echo "Hello<br>";
}
}
$obj= new Example();
?>
Parameterized Constructor:
A constructor with parameters is known as parameterized constructor. It means we can pass different values to initialize the data members of the class. The following example program will help you to understand Parameterized PHP Constructor.
<?php
class Example{
//defining constructor
function __construct($name) {
echo "Hello ".$name."<br>";
}
}
$obj1= new Example("World");
$obj2= new Example("Owlbuddy");
?>
Copy Constructor:
The copy constructor is used to create a copy of an already existing object. It takes the address of the other objects as a parameter.
<?php
class Example {
public $name;
public $age;
//default constructor
public function __construct() {
}
// This is a copy constructor
public function copyCon(Example $o)
{
$this->name = $o->name;
$this->age = $o->age;
}
function show() {
echo "Name = ".$this->name.'<br>';
echo "Age = ".$this->age.'<br>';
}
}
$obj1 = new Example();
$obj1->name = 'Aman';
$obj1->age = '21';
$obj1->show();
$obj2 = new Example();
//calling copyCon method
$obj2->copyCon($obj1);
$obj2->show();
?>