can you have more than one constructor in class php

Solutions on MaxInterview for can you have more than one constructor in class php by the best coders in the world

showing results for - "can you have more than one constructor in class php"
Erica
29 Mar 2017
1WORK AROUND
2
3<?php
4
5class Animal
6{
7    public function __construct()
8    {
9        $arguments = func_get_args();
10        $numberOfArguments = func_num_args();
11
12        if (method_exists($this, $function = '__construct'.$numberOfArguments)) {
13            call_user_func_array(array($this, $function), $arguments);
14        }
15    }
16   
17    public function __construct1($a1)
18    {
19        echo('__construct with 1 param called: '.$a1.PHP_EOL);
20    }
21   
22    public function __construct2($a1, $a2)
23    {
24        echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL);
25    }
26   
27    public function __construct3($a1, $a2, $a3)
28    {
29        echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL);
30    }
31}
32
33$o = new Animal('sheep');
34$o = new Animal('sheep','cat');
35$o = new Animal('sheep','cat','dog');
36
37// __construct with 1 param called: sheep
38// __construct with 2 params called: sheep,cat
39// __construct with 3 params called: sheep,cat,dog
40