Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 409
hoyomi Avatar asked May 13 '11 01:05

hoyomi


People also ask

Can a constructor have more than one parameter?

The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.

How many parameters can a constructor take?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.

Can a PHP class have more than one constructor?

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

How many parameters is too many in a constructor?

You might actually come close to the technical limit of 255 parameters for constructors and other units.


1 Answers

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).

like image 154
Tadeck Avatar answered Oct 22 '22 08:10

Tadeck