Polymorphism in php

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 i will show you how you can achieve method overloading in PHP.

<?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;
}
}
}

function rawr()
{
echo “rawr”;
}

function sayArray($arr)
{
foreach($arr as $s)
{
$this->saySentence($s .”. “);
}
}

function sayNothing()
{
echo “I have nothing to say.”;
}

function saySentence($sentence)
{
echo $sentence;
}

function sayTwo($first,$second)
{
echo $first . “.<br/>” . $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’));

Bit clumsy isn’t it but you still you will get the flavor of  method overloading. Enjoy……..

Advertisement

~ by Kal Purush on September 23, 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.