PHP is an object-oriented scripting language, and we all know that object-oriented language has three main features: encapsulation, inheritance, polymorphism. PHP is supposed to have these three big features.
Encapsulation is the process of building a class, PHP has, and PHP has inherited features. Only this polymorphic, PHP embodies very vague. The reason is that PHP is a weakly typed language.
The polymorphic embodiment of Java is very clear, broadly divided into two categories: the parent class refers to the subclass object, and the interface reference to the class object that implements the interface. When Java declares a variable, it sets the type of the variable, so what is the parent class reference and the interface reference. PHP does not have this, the PHP declaration variable does not need to set the variable type, a variable can point to different data types. Therefore, PHP does not have the same polymorphism as Java.
PHP does not have a clear polymorphism like Java, and does not mean that PHP is not polymorphic. Take a look at the following example:
1 abstract class animal{2 abstract function Fun (), 3} 4 class Cat extends animal{5 function Fun () {6 echo ' Cat say Miaomiao ... "; 7 } 8} 9 class Dog extends animal{10 function fun () {One echo "dog say Wangwang ...";}13 }14 function wor K ($obj) { if ($obj instanceof animal) {$obj-fun (); }else{18 echo "no function"; }21 Work (New Dog ()); Work (New Cat ());
The above is judged by a keyword instanceof, whether the object pointed to by the variable is an instance of the animal class, the following new Cat (), new Dog () are objects of the animal subclass, and output "dog say Wangwang ..." and "Cat say Miaomiao ... ", stating that the subclass object is an instance of the parent class, thus achieving the functionality of Java polymorphism.
The upper class is an abstract class, which also indicates that the interface and the class object that implements the interface can also be applied.
At this point, it is concluded that although the multi-state of PHP is fuzzy, it still has polymorphic characteristics.
PHP Multi-State understanding