HomePHP Page 2 - Using Inheritance, Polymorphism and Serialization with PHP Classes
Polymorphism - PHP
If you are working with classes in PHP, you will sooner or later encounter inheritance, polymorphism, and serialization. The ability to use these three will help speed up your code writing. This article covers how to use them, and more.
The idea of polymorphism is that when we look at an object, and ask it to do something, like call one of its methods, we do not really need to know how a class works or exactly how it does its internal workings. We need to know how it works and what it does when we are defining the class and writing the methods, but we do not need to know, as programmers making use of the object, exactly how it all happens.
For instance, we can have two different objects with methods that have the same name, which will do similar things -- but with a difference depending on the kind of object we call the method from. The principal of polymorphism states that we do not need to specify anything different when we ask the object to do whatever it is that we want it to do. To demonstrate, let's make some changes to our human class:
class human{ function human($hcolor){ $this->hcolor=$hcolor; } function say_hello(){ echo "Hello!<br>"; } var $legs=2; function report(){ return "This <b>".get_class($this)."</b> has <b>" .$this- >hcolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ; } } class African extends human{ var $hcolor="black"; function African() {} } //instantiate the class $jude = new human("black"); $jane = new african(); $jude->legs++; //increase legs by one echo $jane->say_hello(); echo $jude->say_hello();
If we want the African class to say something other than hello, here’s what we do:
class human{ function human($hcolor){ $this->hcolor=$hcolor; } function say_hello(){ echo "Hello!<br>"; } var $legs=2; function report(){ return "This <b>".get_class($this)."</b> has <b>" .$this- >hcolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ; } } class African extends human{ var $hcolor="black"; function African() {} function say_hello(){ echo “Hello there!” } } //instantiate the class $jude = new human("black"); $jane = new african(); $jude->legs++; //increase legs by one echo $jane->say_hello(); echo $jude->say_hello();
We asked both objects to say hello using exactly the same syntax and it worked as expected. This is important in object oriented programming because it allows the object to take control of the way it works. In other words, we can make the same request of two different objects, and based on the different workings of the two objects, we end up with two (possibly different) results. This makes coding cleaner and more intuitive.