Why can't I overload constructors in PHP?
I have abandoned all hope of ever being able to overload my constructors in PHP, so what I'd really like to know is why.
Is there even a reason for it? Does it create inherently bad code? Is it widely accepted language design to not allow it, or are other languages nicer than PHP?
Solution 1:
You can't overload ANY method in PHP. If you want to be able to instantiate a PHP object while passing several different combinations of parameters, use the factory pattern with a private constructor.
For example:
public MyClass {
private function __construct() {
...
}
public static function makeNewWithParameterA($paramA) {
$obj = new MyClass();
// other initialization
return $obj;
}
public static function makeNewWithParametersBandC($paramB, $paramC) {
$obj = new MyClass();
// other initialization
return $obj;
}
}
$myObject = MyClass::makeNewWithParameterA("foo");
$anotherObject = MyClass::makeNewWithParametersBandC("bar", 3);
Solution 2:
You can use variable arguments to produce the same effect. Without strong typing, it doesn't make much sense to add, given default arguments and all of the other "work arounds."
Solution 3:
For completeness, I'll suggest Fluent Interfaces. The idea is that by adding return $this;
to the end of your methods you can chain calls together. So instead of
$car1 = new Car('blue', 'RWD');
$car2 = new Car('Ford', '300hp');
(which simply wouldn't work), you can do:
$car = (new Car)
->setColor('blue')
->setMake('Ford')
->setDrive('FWD');
That way you can pick exactly which properties you want to set. In a lot of ways it's similar to passing in an array of options to your initial call:
$car = new Car(['make' => 'Ford', 'seats' => 5]);