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?
True overloading is indeed unsupported in PHP. As @Pestilence mentioned, you can use variable arguments. Some people just use an Associative Array of various options to overcome this.
?>
PHP Manual: Function Arguments, Default Values
I have overcome this simply by using default values for function parameters. In
__constuct
, list the required parameters first. List the optional parameters after that in the general form$param = null
.This can be instantiated as:
or
This is not a perfect solution, but I have made this work by separating parameters into absolutely mandatory parameters no matter when the object is constructed, and, as a group, optional parameters listed in order of importance.
It works.
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(which simply wouldn't work), you can do:
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:
As far as I know, constructor overloading in PHP is not allowed, simply because the developers of PHP did not include that functionality - this is one of the many complaints about PHP.
I've heard of tricks and workarounds, but true overloading in the OOP sense is missing. Maybe in future versions, it will be included.
I'm really no OOP expert, but as I understand it overloading means the ability of a method to act differently depending in the parameters it receives as input. This is very much possible with PHP, you just don't declare the input types since PHP does not have strong typing, and all the overloading is done at runtime instead of compile time.