1. What is polymorphism?
Polymorphism actually means executing different methods according to different parameters.
2. Polymorphism in PHP
The concept of polymorphism is generally discussed in strongly typed languages, because strongly typed languages must declare parameters. Type, for example, the parameters of the open method of a flashlight object state that it can only be blue light, and cannot pass other lights. But you can use parent class rendering to make it polymorphic. For example, declare a parent class of light, let other colors of light inherit from this light parent class, declare its parameters as the parent class light, and then pass any subclass of light Either way, this is strongly typed polymorphism.
But PHP is a weakly typed dynamic language and does not detect parameter types. You can pass anything; but in the PHP5.3 version, you can declare parameters as certain objects; when declaring parameters as instantiated objects of a certain class , you have to use the parent class rendering method to make it polymorphic;
3. Understanding of PHP polymorphism
php is an object-oriented scripting language, and we all As you know, object-oriented languages have three major characteristics: encapsulation, inheritance, and polymorphism. PHP should have these three characteristics.
Encapsulation is the construction process of a class, which PHP has; PHP also has the feature of inheritance. Only this polymorphism is very vague in PHP. The reason is that php is a weakly typed language.
Java's polymorphism is very clear and can be roughly divided into two categories: parent class references point to subclass objects; interface references point to class objects that implement the interface. When declaring a variable in Java, you must set the type of the variable, so what parent class references and interface references exist. This is not reflected in PHP. When declaring a variable in PHP, you do not need to set a type for the variable. A variable can point to different data types. So, php does not have polymorphism like java.
php does not have clear polymorphism like java, it does not mean that php does not have polymorphism. Look at the following example:
abstract class animal{ abstract function fun(); } class cat extends animal{ function fun(){ echo "cat say miaomiao..."; } } class dog extends animal{ function fun(){ echo "dog say wangwang..."; } } function work($obj){ if($obj instanceof animal){ $obj -> fun(); }else{ echo "no function"; } } work(new dog()); work(new cat());
The above class is an abstract class, which also shows that interfaces and class objects that implement interfaces can also be applied.
Recommended tutorial: PHP video tutorial
The above is the detailed content of Is php polymorphic?. For more information, please follow other related articles on the PHP Chinese website!