phpconstructormultiple-constructors

How to implement php constructor that can accept different number of parameters?


How to implement php constructor that can accept different number of parameters?

Like

class Person {
    function __construct() { 
        // some fancy implementation
    } 
} 

$a = new Person('John');
$b = new Person('Jane', 'Doe');
$c = new Person('John', 'Doe', '25');

What is the best way to implement this in php?

Thanks, Milo


Solution

  • One solution is to use defaults:

    public function __construct($name, $lastname = null, $age = 25) {
        $this->name = $name;
        if ($lastname !== null) {
            $this->lastname = $lastname;
        }
        if ($age !== null) {
            $this->age = $age;
        }
    }
    

    The second one is to accept array, associative array or object (example about associative array):

    public function __construct($params = array()) {
        foreach ($params as $key => $value) {
            $this->{$key} = $value;
        }
    }
    

    But in the second case it should be passed like this:

    $x = new Person(array('name' => 'John'));
    

    The third option has been pointed by tandu:

    Constructor arguments work just like any other function's arguments. Simply specify defaults php.net/manual/en/… or use func_get_args().

    EDIT: Pasted here what I was able to retrieve from original answer by tandu (now: Explosion Pills).