PHP Constructor

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.

Syntax of PHP Constructor Function

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, 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 myClass
{
// Defining constructor function
function __construct()
{
// Display message when object gets created.
echo "Object is created...";
}
}
// Creating object
$myclass = new myClass;
?>