Home » PHP » What is the Polymorphism in PHP?

What is the Polymorphism in PHP?

Polymorphism is one of the PHP Object Oriented Programming (OOP) features. Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). In general, polymorphism means the ability to have many forms. In other words, “Polymorphism describes a pattern in Object Oriented Programming in which a class has varying functionality while sharing a common interfaces.”. There are two types of Polymorphism which are given below: 

  1. Compile time (function overloading)
  2. Run time (function overriding)

But PHP “does not support” compile time polymorphism, which means function overloading and operator overloading.

interface A {
	public function name();
}

class B implements A {
	public function name() {
		echo "I am a B<br>";
	}
}

class C implements A {
	public function name() {
		echo "I am a C";
	}
}

function x(A $a) {
	$a->name();
}

x(new B()); // I am a B
x(new C()); // I am a C

Check Also

What is the inheritance in PHP?

Inheritance is the process in which object of one class acquire the properties of another …

Leave a Reply

Your email address will not be published. Required fields are marked *