PHP Class Constructor
Definition
A constructor is a special method that is called by PHP when you create an instance of the class.
Syntax
PHP class constructor has the following syntax.
public function __construct(Optional Parameter) {}
Example 1
<?PHP/* ww w . j av a 2s . c o m*/
class MyClass {
function __construct() {
echo "I am being constructed.";
}
}
$obj = new MyClass;
?>
The code above generates the following result.
The class, MyClass , contains a very simple constructor that just displays the message. When the code then creates an object from that class, the constructor is called and the message is displayed.
Example 2
You can pass arguments to constructors, like normal methods.
<?PHP/*from w ww. ja va 2s . c o m*/
class Person {
private $_firstName;
private $_lastName;
private $_age;
public function __construct( $firstName, $lastName, $age ) {
$this-> _firstName = $firstName;
$this-> _lastName = $lastName;
$this-> _age = $age;
}
}
$p = new Person( "James", "Bond", 28 );
?>
The Person class contains three private properties and a constructor that accepts three values, setting the three properties to those values.
Example 3
If a class contains a constructor, it is only called if objects are created from that class.
If an object is created from a child class, only the child class's constructor is called.
To make a child class call its parent's constructor call parent::__construct().
<?PHP//from w w w .j av a 2 s. c om
class NameTag {
public $Words;
}
class Book {
public $Name;
public function say() {
print "Woof!\n";
}
public function __construct($BookName) {
print "Creating a Book: $BookName\n";
$this->Name = $BookName;
}
}
class ComputerBook extends Book {
public function say() {
print "Computer!\n";
}
public function __construct($BookName) {
parent::__construct($BookName);
print "Creating a computer book\n";
}
}
?>
It is better to call parent::__construct()
first from
the constructor of a child class, in order to set up all the parent's properties.