According to some people, polymorphism is one of the most crucial aspects of objectoriented programming. Describing real-life situations has become simple because you can use inheritance and classes in your codes. PHP codes are not just simple collections of data and functions. Polymorphism can do a lot of things for you. For example, it can help you complete projects by reusing codes or write powerful programs with minimal control statements. Analyze the following example:
<?php
class Bird{
function tweet(){
print "Tweeting (I am a bird) \n";
}
}
class Dog{
function bark(){
print "Barking (I am a dog) \n";
}
}
class Cat{
function meow(){
print "Meowing (I am a cat) \n";
}
}
function makeSound($object){
if($object instanceof Bird){
$object -> tweet();
}elseif($object instanceof Dog){
$object -> bark();
}elseif($object instanceof Cat){
$object -> meow();
}else{
"No valid input \n";
}
}
makeSound(new Dog());
makeSound(new Bird());
makeSound(new Cat());
?>
If you run this script the result will be the following:
Barking (I am a dog)
Tweeting (I am a bird)
Meowing (I am a cat)
This actually works but with polymorphism we can do it better. Polymorphism can simplify the task given above. Basically, this feature allows you to pass
the contents of a class to other classes. Here, you can pass the properties and methods of a class to the new classes you want to create.
At this point, you need to create a class, name it “Animals”, and establish relationships between this parent class and its specific objects. You can perform this inheritance by typing “extends” (i.e. another PHP keyword). Here’s the syntax:
classChildClassextendsParentClass{
…
}
Let’s use “inheritance” to rewrite the code given earlier:
<?php
classAnimals{
function sound(){
print "Each animal will implement its respective sound \n";
}
}
classDogextendsAnimals{
function sound(){
print "I am barking (I am a dog) \n";
}
}
classCatextendsAnimals{
function sound(){
print "I am meowing (I am a little cat) \n";
}
}
classBirdextendsAnimals{
function sound(){
print "I am tweeting (I am a bird) \n";
}
}
function makeSound($object){
if($objectinstanceofAnimals){
$object->sound();
}else{
print "The object is invalid, please check it out \n";
}
}
makeSound(newDog());
makeSound(newCat());
makeSound(newBird());
?>
You will get the following output
I am barking (I ama dog)
I am meowing (I ama little cat)
I am tweeting (I ama bird)
With this approach, you don’t have to alter “rightSound()” regardless of the number of animals you want to add to the code. That’s because “instanceof Animals” covers any animal that you might add.
I hope this article have been useful for you.