Writing the constructor ijn PHP

Started by chinmay.sahoo, 12-28-2015, 00:24:57

Previous topic - Next topic

chinmay.sahooTopic starter

The constructor is a special method that is executed when an object is created using the class as a pattern. A constructor is not required, and you don't need to use a constructor if you don't want to set any property values or perform any actions when the object is created. Only one constructor is allowed.


The constructor has a special name so that PHP knows to execute the method when an object is created. Constructors are named __construct.(Note the two underscores.) A constructor method looks similar to the
following ...

Quotefunction __construct()
{
$this->gas = 10; # starts with a full gas tank
$this->openDoor();
}

This constructor defines the new car. When the car is created, it has a full gas tank and an open door.

Prior to PHP 5, constructors had the same name as the class. You may run across classes written in this older style. PHP 5 looks first for a method called __construct() to use as the constructor. If it doesn't find one, it looks for a method that has the same name as the class and uses that method for the constructor. Thus, older classes still run under PHP 5.