Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Created October 14, 2019 12:40
Show Gist options
  • Save junaidtk/506636c52a6659190baf06bbd7155511 to your computer and use it in GitHub Desktop.
Save junaidtk/506636c52a6659190baf06bbd7155511 to your computer and use it in GitHub Desktop.
__construct() in php
Introduced in the PHP 5.
PHP will call this method, when ever we create a new object. So it is used for the any initialisation before object start.
Parent constructors are not called implicitly in the child class. In order to get the parent constructors in child class
we need to add the statement parent::__construct() within the child constructor.
If the child doesn't contain any __construct(), then the parent class __construct() method will be inherited.
<?php
class grandpa{
public function __construct(){
echo "I am in Tutorials Point"."\n";
}
}
class papa extends grandpa{
public function __construct(){
parent::__construct();
echo "I am not in Tutorials Point";
}
}
$obj = new papa();
?>
Output:
I am in Tutorials Point
I am not in Tutorials Point
<?php
class grandpa{
public function __construct(){
echo "I am in Tutorials point";
}
}
class papa extends grandpa{
}
$obj = new papa();
?>
Output:
I am in Tutorials point
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment