This article mainly introduces PHP multi-state code instances. This article uses two code instances to demonstrate the polymorphism in PHP. For more information, see the following multi-state definition: Only one interface or a base class is concerned, does not care about the specific class of an object. (Same type, different results)
Here are two examples:
First, we found that the base class defines standards and sub-classes implement self-rules. This is a requirement for polymorphism. At the same time, this satisfies rewriting; in fact, this is different performance of different classes; it does not strictly satisfy an interface, or it is a base class programming. This is because the method you call is not stu-> showGrade () but your own method;
class stu{ public function showGrade(){ echo "base class"; }}class xiaomin extends stu{ public function showGrade(){ echo "is son show 80"; } }class xiaoli extends stu{ public function showGrade(){ echo "is son show 60"; } }function doit($obj){ if(get_class($obj) != "stu"){ $obj->showGrade(); }}doit(new xiaoli());doit(new xiaomin());
Example 2: The dovoice parameter specifies that $ obj is an animal, and consciousness means that the implementation class object is accepted by the interface. Is transformed upwards. This is consistent with the same type and different results. This is polymorphism;
In Java, it will be like animal a = new dog (); Because PHP is a type language. There is no object transformation mechanism.
interface animal{ public function voice();}class cat implements animal{ public function voice(){ echo "miao~~~
"; }}class dog implements animal{ public function voice(){ echo "wang ~~~
"; }}function dovoice(animal $obj){ $obj->voice();}dovoice(new dog());dovoice(new cat());