You are very happy to hear that PHP supports OOP and decided to spend your holiday by exploring the Object Oriented Feature of PHP. But suddenly you got stuck to write method overloading and also became furious for the absence of Late static binding(Lazy Binding).But don't be worried, the later would be solved in PHP v6 and now a little example how we can achieve method overloading in PHP.
class overloading
{
function __call($method, $args)
{
if($method == 'talk') {
if(count($args) == 0) {
$this->sayNothing();
}
elseif(count($args) == 1) {
if(is_array($args[0])) {
$this->sayArray($args[0]);
}
else {
$this->saySentence($args[0]);
}
}
elseif(count($args) == 2) {
$this->sayTwo($args[0], $args[1]);
}
else {
return false;
}
}
}
public function function rawr()
{
echo "rawr";
}
protected function sayArray($arr)
{
foreach($arr as $s) {
$this->saySentence($s .". ");
}
}
protected function sayNothing()
{
echo "I have nothing to say.";
}
protected function saySentence($sentence)
{
echo $sentence;
}
protected function sayTwo($first,$second)
{
echo $first . ".
;" . $second . ".";
}
}
$o = new overloading();
$o->rawr();
$o->talk('a sentence');
$o->talk('a sentence','another sentence');
$o->talk(array('hello I am joey.','nice to meet you'));
No comments:
Post a Comment