This tutorial helps you learn how to use the PHP constructor for initialising the properties of an object.
PHP lets developers declare constructor methods for classes. On creating an object of any class, you need to set the properties of that object before using it. To do this, you first need to initialise the object and then set values for the properties either by using the public setter methods for the private variables or by using the - > operator if the variables are public.
PHP offers a special method known as Constructor for creating and initialising a class object in a single step. A constructor is used for constructing an object by assigning the required property values when creating an object.
The destructor method is used for destroying the object.
<?php
class <CLASS_NAME> {
// constructor
function __construct()
{
// initialize the object properties
}
}
?>
Arguments are accepted by constructors. However, destructors will not have any arguments because a destructor destroys the current object reference.
For example, let's take a class Person having two properties, lname, and fname. For this class, let's define a constructor to initialise the class properties (Variables) at the time of object creation.
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// public method to show name
public function showName() {
echo "My name is: " . $this->fname . " " . $this->lname;
}
}
// creating class object
$john = new Person("Justin", "Drake");
$john->showName();
?>
Initialising the object...
My name is Justin Drake
While earlier, the - > operator method was used to set value for the variables, or the setter method was used, in the constructor method's case, values can be assigned to the variables at the time of object creation.
In case the class has a constructor, then, in that case, a constructor is called whenever an object of that class is created.
Since function overloading is not supported by PHP, therefore, you cannot have multiple implementations for constructor in a class.