Open In App

How to mimic multiple constructors in PHP ?

Constructors are special member functions for initial settings of newly created object instances from a class. 

In PHP, a constructor is a method named __construct(), which is called by the keyword new after creating the object. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor arguments for the parameters.



Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables.

Constructor types:



Note: PHP lacks support for declaring multiple constructors of different numbers of parameters for a class unlike languages such as Java.

Multiple Constructors: More than one constructor in a single class for initializing instances are available.

Example 1: In the following example, we create a script and try to declare multiple constructors. We will assign the name of a student using one constructor and age with another constructor.




<?php
class Student {
     
    // Constructor with 1 parameter
    public function __construct(string $name) {
          
    }
  
    // Constructor with 2 parameters
    public function __construct(string $name, string $age) {
          
    }
}
  
$obj1 = new Student('Akshit');
$obj2 = new Student('Akshit', '12');
  
?>

Output:

PHP Fatal error:
Cannot redeclare Student::__construct() in 
/home/33a7c36527d199adf721ab261035d4f7.php on line 10

We have to use different methods to use Multiple Constructors in PHP. Some are listed below.

Approach:

Example 2:




<?php
  
class Student {
  
    public function ConstructorWithArgument1($arg1) {
        echo('Constructor with 1 parameter called: '.$arg1)."<br>";
    }
      
    public function ConstructorWithArgument2($arg1, $arg2) {
        echo('Constructor with 2 parameters called: 
            '.$arg1.','.$arg2)."<br>";
    }
      
    public function ConstructorWithArgument3($arg1, $arg2, $arg3) {
        echo('Constructor with 3 parameters called: 
        '.$arg1.','.$arg2.','.$arg3)."<br>";
    }
    public function __construct() {
        $arguments = func_get_args();
        $numberOfArguments = func_num_args();
  
        if (method_exists($this, $function
                'ConstructorWithArgument'.$numberOfArguments)) {
            call_user_func_array(
                        array($this, $function), $arguments);
        }
    }
}
  
// Constructor with 1 parameter
$obj = new Student('Akshit'); 
  
// Constructor with 2 parameters
$obj = new Student('Akshit','Nikita'); 
  
// Constructor with 3 parameters 
$obj = new Student('Akshit','Nikita','Ritesh'); 
  
?>

Output
Constructor with 1 parameter called: Akshit
Constructor with 2 parameters called: Akshit,Nikita
Constructor with 3 parameters called: Akshit,Nikita,Ritesh

Approach:

Example 3: The following example demonstrates multiple constructors with different data types like string or integer.




<?php
class Student {
  
    public $id;
    public $name;
    // etc.
   
    public function __construct($idOrName) {
      
        if(is_int($idOrName)) {
              
            $this->id=$idOrName;
            echo "ID is initialized using constructor"."<br>";
            // other members are still uninitialized
        }
        else {
            $this->name = $idOrName;
            echo "Name is initialized using constructor"."<br>";
        }
    }
     
    public function setID($id) {
        $this->id = $id;
    }
     
    public function setName($name) {
        $this->name = $name;
    }
     
    public function getinfo() {
        echo "ID : ". $this->id."<br>";
        echo "Name : ". $this->name."<br>";
    }
}
   
// Create instance
$student = new Student("Akshit");
$student->setID(1);
$student->getinfo();
   
$student2 = new Student(2);
$student2->setName("Nikita");
$student2->getinfo();
  
?>

Output
Name is initialized using constructor
ID : 1
Name : Akshit
ID is initialized using constructor
ID : 2
Name : Nikita

Article Tags :