Polymorphism in PHP
- 2020年12月07日
- 技術情報
Polymorphism sounds difficult in terms of its vocabulary but it’s not that complex. Today I will write some explanations along with simple code examples. There are two types of polymorphism called dynamic polymorphism and static polymorphism.
Let’s take a look at the dynamic polymorphism first. It can be achieved using interface.
<?php
interface Country
{
public function talk();
}
class Myanmar implements Country
{
public function talk()
{
return "Mingalarpr";
}
}
class Japan implements Country
{
public function talk()
{
return "ko ni chi wa";
}
}
?>
There is an interface called Country and two of the concrete classes called Myanmar and Japan implemented it. The type of two concrete classes, Myanmar & Japan are same as they are the country but the function called talk inside their classes will be different depending on the country.
$myanmar = new Myanmar();
$japan = new Japan();
echo $myanmar->talk(); //output - Mingalarpr
echo $japan->talk(); //output - ko ni chi wa
As I said earlier before their talk function is different. That is called dynamic polymorphism. Concrete classes are sharing the same interface as they are common in type but different in functionalities.
There is one more polymorphism called static polymorphism. This can be achieved using method overloading. We will use __call magic method as we are writing in PHP.
<?php
class Talk
{
function __call($name,$arg){
switch(count($arg)){
case 1 : return $arg[0];
case 2 : return $arg[0] . '&' .$arg[1];
}
}
}
$talk = new Talk();
echo $talk->lang("Myanmar"); //output - Myanmar
echo $talk->lang("Myanmar","Japan"); //output Myanmar & Japan
There are different return depending on the method arguments. The class talk can be adaptable depending on the function arguments which is called static polymorphism.
You can see the magic method __call reference here.
https://www.php.net/manual/en/language.oop5.overloading.php#object.call
Thanks for reading. By Yuuma.
yuuma at 2020年12月07日 11:00:11