PHP Tutorial PHP Advanced PHP References

PHP - Constructors



A constructor is a special method of a class which automatically executed when a new object of the class is created. It allows the class to initialize an object's properties and allocate memory.

The PHP __construct() function is a reserved built-in function also called class constructor. It is automatically executed when a new instance of class is created. It allows the class to initialize object's properties or other operations which is needed to create an object. Please note that it starts with two underscores (__).

When a constructor is not specified in a class, compiler generates a default constructor and inserts it into the code. However, it does not initialize the object's properties.

Syntax

function __construct(parameters) {
  statements;
}

Example:

In the example below, a class called person is created. A constructor is also created which is used to initialize the object's property name and city of the class.

<?php
class person {
  private $name;
  private $city;
  function __construct($name, $city) {
    $this->name = $name;
    $this->city = $city;
  }
  public function info() {
    echo $this->name." lives in ".$this->city.".\n";     
  }   
};

$p1 = new person('John', 'London');
$p1->info(); 

$p2 = new person('Marry', 'New York');
$p2->info();  
?>

The output of the above code will be:

John lives in London.
Marry lives in New York.