oop - Overloading construct in php?
929
does php (5.3.7) supports overloading ?
Example:
class myclass{
function __construct($arg1) { // Construct with 1 param}
function __construct($arg1,$arg2) { // Construct with 2 param}
}
new myclass(123); //> call the first construct
new myclass(123,'abc'); //> call the second
Answer
Solution:
You have to implement the constructor once and use
func_get_args
andfunc_num_args
like this:This way you can support any number of arguments.
Answer
Solution:
No, but it supports optional parameters, or variable number of parameters.
Note that this has the downside that if you actually want to be able to supply
null
as a second parameter it will not accept it. But in the remote case you want that you can always use thefunc_*
family of utils.Answer
Solution:
I would define some
fromXXX
methods that call the__constructor
which takes a parameter likeid
.