Directly PHP don't supports method overloading, but we can implement this feature with func_get_args():
class Obj
{
function __construct() {
$args = func_get_args();
if (count($args) != 2) {
echo ("Must be passed two arguments !\n");
return;
}
if (is_numeric($args[0]) && is_numeric($args[1])) {
$result = $this->_addnum($args[0], $args[1]);
}
else if (is_string($args[0]) && is_string($args[1])) {
$result = $this->_addstring($args[0], $args[1]);
}
else if (is_bool($args[0]) && is_bool($args[1])) {
$result = $this->_addbool($args[0], $args[1]);
}
else if (is_array($args[0]) && is_array($args[1])) {
$result = $this->_addarray($args[0], $args[1]);
}
else {
echo ("Argument(s) type is not supported !\n");
return;
}
echo "\n";
var_dump($result);
}
private function _addnum($x, $y) {return $x + $y;}
private function _addstring($x, $y) {return $x . $y;}
private function _addbool($x, $y) {return $x xor $y;}
private function _addarray($x, $y) {return array_merge($x,$y);}
}
// invalid constructor cases
new Obj();
new Obj(null, null);
// valid ones
new Obj(2,3);
new Obj('A','B');
new Obj(false, true);
new Obj([3], [4]);
Outputs :
Must be passed two arguments !
Argument(s) type is not supported !
int(5)
string(2) "AB"
bool(true)
array(2) {
[0] =>
int(3)
[1] =>
int(4)
}