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
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.
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
Multiple Constructors: More than one constructor in a single class for initializing instances are available.
You might actually come close to the technical limit of 255 parameters for constructors and other units.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With