Php Polymorphism

What is Php Polymorphism?

In general, polymorphism is the ability to appear in different forms. Technically, it is the ability to redefine methods for derived classes.

Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms.

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

Why method polymorphism cannot be achieved?
The reason why polymorphism for methods is not possible in PHP is because you can have a method that accepts two parameters and call it by passing three parameters. This is because PHP is not strict and contains methods like func_num_args() and func_get_arg() to find the number of arguments passed and get a particular parameter.
Because PHP is not type strict and allows variable arguments, this is why method polymorphism is not possible.

Note:- polymorphism is possible with class methods. The basis of polymorphism is Inheritance and overridden methods.

In the below example method taste is different for different class, for Apple class, method show sweet taste and for class Orange method taste show sour so this is follow one name many form (Polymorphism).


<?php
interface fruit {
	public function taste();
}

class Apple implements fruit {
	public function taste() {
		return 'Apple taste is very sweet.';
	}

}

class Orange implements fruit {
	public function taste() {
		return 'Orange taste is very sour.';
	}

}


$app_Obj = new Apple;
echo $app_Obj -> taste();

$orange_Obj = new Orange;
echo $orange_Obj -> taste();
?>
Output:- Apple taste is very sweet.
Orange taste is very sour.