This tutorial describes the constructor method for classes in PHP. It shows through an example program how the constructor works in a class and how to pass parameters to it.
What Is a Class Constructor?
PHP allows developers to declare constructor methods for classes. A constructor is a generic method associated with a class that gets called automatically for each newly created object of the class instance. It is like other member methods in a class, the only difference being that it is only for specific instructions that must be executed when creating class instances.
Pass Arguments to a Constructor
Like any other function, a constructor can also define some arguments that the developer may need later in the program. And if a constructor doesn't have the required arguments or a class doesn't need a constructor, it can also be written empty, or the best option is not to write it because a constructor is mainly used to create and initialize objects.
Example:
PHP script to demonstrate constructor method with Parameters:
<?php
/*Example Class*/
class Example
{
public $Name, $Age;
/*Constructor method with arguments*/
public function __construct($UserName, $UserAge)
{
$this->Name = $UserName;
$this->Age = $UserAge;
}
}
/*Create the class object*/
$Obj1 = new Example("Tom", 22);
$Obj2 = new Example("Dick", 26);
$Obj3 = new Example("Harry", 28);
/*Print*/
print_r([$Obj1, $Obj2, $Obj3]);
?>
Program Output:
Array ( [0] => Example Object ( [Name] => Tom [Age] => 22 ) [1] => Example Object ( [Name] => Dick [Age] => 26 ) [2] => Example Object ( [Name] => Harry [Age] => 28 ) )