What is a Constructor in PHP?

In PHP, the constructor is used to initialize the object of properties,
In other words, we can say that it automatically calls when the object will be initializing.
If a class name and function name are similar in that case function is known as constructor.
We can create a constructor by using the "__construct" Keyword.

 

Example1
<?php
class Car{
  function CarModel(){
      echo "This is the CarModel function. It will automatically invoke";
  }
  function Car(){
      echo "User Defined Constructor (Class name and function Car() name is same )"."<br>";
  }
}
$obj= new Car();
$obj->CarModel();
?>
Output
User Defined Constructor (Class name and function Car() name is same )
This is the CarModel function. It will automatically invoke

 

Example2
<?php
class Car{
  function CarName(){
      echo "Car Name- Thar";
  }
  function __construct(){
      echo "This is predefined constructor"."<br>";
  }
}
$obj= new Car();
$obj->CarName();
?>
Output
This is the predefined constructor
Car Name- Thar

 

Example 3
<?php
class Car{
  public $name;
    function __construct($name){
      $this->name = $name;
  }
  function get_name(){
      return $this->name;
  }
}
$obj= new Car("THAR");
echo $obj->get_name();
?>
Output
THAR
 


Prev Next