• Post category:PHP

How do we Create PHP Constructor Function

PHP Constructor Function

Constructor functions are a special type of function that is called automatically whenever an object is created. We can pass as many as arguments to the constructor function. PHP has a  constructor function called “__construct” to define the PHP constructor.

Ex:

function __construct($s , $p)
{
$this->title = $t;
$this->price = $p }

Here, we don’t need to call the set function separately to set the price and title which is demonstrated in classes. We can initialize these two member variables at the time of object creation only.

$physics = new Books("Physics for High School", 100);
$maths = new Books("Advanced chemistry", 150);

//Get those set values
$physics->getTitle();
$physics->getPrice();
$maths->getTitle();
$maths->getPrice();

Output:

Physics for High School
100
Advanced Chemistry
150

Leave a Reply