- PHP 5 allows developers to declare constructor methods for classes.
- Constructor is suitable for any initialization that the object may need before it is used.
- We can design constructor using "__construct" or same name as class name.
- Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct().
Example 1
snippet
<?php
class Example
{
public function __construct()
{
echo "Hello rookienerd";
}
}
$obj = new Example();
$obj = new Example();
?>
Output:
Example 2
snippet
<?php
class demo
{
public function demo()
{
echo "constructor1...";
}
}
class demo1 extends demo
{
public function __construct()
{
echo parent::demo();
echo "constructor2...";
}
}
$obj= new demo1();
?>
Output: