O'Reilly logo

PHP 5 Power Programming by Derick Rethans, Stig Sæther Bakken, Andi Gutmans

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.9. Polymorphism

The subject of polymorphism is probably the most important in OOP. Using classes and inheritance makes it easy to describe a real-life situation as opposed to just a collection of functions and data. They also make it much easier to grow projects by reusing code mainly via inheritance. Also, to write robust and extensible code, you usually want to have as few as possible flow-control statements (such as if() statements). Polymorphism answers all these needs and more.

Consider the following code:

 class Cat { function miau() { print "miau"; } } class Dog { function wuff() { print "wuff"; } } function printTheRightSound($obj) { if ($obj instanceof Cat) { $obj->miau(); } else if ($obj instanceof Dog) { $obj->wuff(); } else { print ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required