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.
- Default Constructor: It has no parameters, but the values to the default constructor can be passed dynamically.
- Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members.
- Copy Constructor: It accepts the address of the other objects as a parameter.
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 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.
- Get all the assigned arguments by using PHP func_get_arg() to get a mentioned value from the argument passed as the parameters.
- We will first count the number of arguments passed to the constructor by using PHP func_num_args().
- By knowing type of arguments using PHP gettype() or data-type specific function like is_int().
- Name your method as per the number of arguments and check its existence using PHP method_exists().
- Call the suitable function using call_user_func_array() by passing the original arguments as call_user_func_array()’s second argument.
Constructor with 1 parameter called: Akshit Constructor with 2 parameters called: Akshit,Nikita Constructor with 3 parameters called: Akshit,Nikita,Ritesh
- Check the type of argument that is passed with the constructor. It can be done using gettype() or data-type specific function like is_int().
- Determine the type and initialize the instance variable.
Example 3: The following example demonstrates multiple constructors with different data types like string or integer.
Name is initialized using constructor ID : 1 Name : Akshit ID is initialized using constructor ID : 2 Name : Nikita