Overloading (which is different from overriding) is not supported in PHP. In OOP you
“overload” a method when you define two/more methods with the same name but different
number or type of parameters (depending upon the language). Php is a loosely typed
language so overloading by types won’t work, however overloading by number of
parameters doesn’t work either.
“overload” a method when you define two/more methods with the same name but different
number or type of parameters (depending upon the language). Php is a loosely typed
language so overloading by types won’t work, however overloading by number of
parameters doesn’t work either.
It’s very nice sometimes in OOP to overload constructors so you can build the object
in different ways (passing different number of arguments). A trick to do something
like that in PHP is:
in different ways (passing different number of arguments). A trick to do something
like that in PHP is:
<?php
class Myclass {
function Myclass() {
$name="Myclass".func_num_args();
$this->$name();
//Note that $this->$name() is usually wrong but here
//$name is a string with the name of the method to call.
}
function
Myclass1($x) {
code;
}
function Myclass2($x,$y) {
code;
}
}
?>
With this extra working in the class the use of the class is transparent to the user:
$obj1=new Myclass('1'); //Will call Myclass1 $obj2=new Myclass('1','2'); //Will call Myclass2
Sometimes this is very nice.