Constructor in PHP

Introduction to PHP Constructor

Constructor is a function that is declared within the class. Whenever a new object of the class is created then the class constructor automatically calls.

Constructor is important for those situations when you want to perform an initialization before using the object such as assigning values ​​to class member variables, connecting to the database, etc.

If PHP does not get the __construct function, then it will find the function named class and try to execute it.

Syntax

Normal syntax of declaring function __construct () in PHP is being given below.

<?php
function __construct($args-list)
{
// Statements to be executed when objects are created.
}
?>

You can use function keyword to declare constructor function like any normal function. After this, by typing double underscore, we write the name of the __construct () function. You can also pass arguments in the Constructor function.

Examples of PHP Constructor

A simple example of creating a constructor in PHP is being given below.

<?php
class Username
{
// Defining constructor function
function __construct()
{
echo "My Name is Khan";
}
}
// Creating object
$myclass = new Username
?>

In the above example, as soon as the object is created, the constructor is called the function call and My Name is Khan .. message display.

Like any normal function I told you, arguments can be passed in the constructor function as well. An example of this is being given below.

<?php
class Number
{
// Defining argument to constructor function
function __construct($num)
{
echo "Object number $num is created";
}
}
// Passing argument to constructor function while creating object
$myclass = new Number(5);
?>