What is polymorphism?
Polymorphism is the third feature of object-oriented languages after database abstraction and inheritance. Polymorphism refers to multiple forms and has the ability to express multiple forms. In object-oriented representations are handled differently depending on the type of object. Polymorphism allows each object to respond to a common message in its own way. Polymorphism enhances software flexibility and reusability.
If we create a doing() method, if it is a student, it will print for class, and if it is a company employee, it will print for work.
Common practice
Use if judgment
/** * PHP多态性 */ // 定义学生类 class student{ public function cla(){ echo "学生工正在上课!<br />"; } } // 定义职员类 class office{ public function Wor(){ echo "职员正在上班!<br />"; } } // 判断对象类型方法 function doing($obj){ if($obj instanceof student){ $obj->cla(); }elseif($obj instanceof office){ $obj->wor(); }else{ echo "没有这个对象!"; } } doing(new student()); // 学生正在上课 doing(new office()); // 职员正在上班
The above result output:
Students are in class
Staff are at work
This ordinary method has a disadvantage, that is, if there are many objects, then if..else.. will be very long and inflexible.
Polymorphism practice
Define a public abstract method, and all subclasses inherit it.
/** * PHP多态性 */ // 定义一个公共类 class pub{ protected function working(){ echo "本方法需要在子类中重载!"; } } // 定义学生类,继承公共类pub class student extends pub{ public function working(){ echo "学生工正在上课!<br />"; } } // 定义职员类,继承公共类pub class office extends pub{ public function working(){ echo "职员正在上班!<br />"; } } // 判断对象类型方法 function doing($obj){ if($obj instanceof pub){ $obj->working(); }else{ echo "没有这个对象!"; } } doing(new student()); // 学生正在上课 doing(new office()); // 职员正在上班
This is the feature of polymorphism, flexible reuse.
Other practices
From the perspective of the implementation of polymorphism, it is nothing more than standardizing that each class must override the parent class A method to achieve a unified effect. When we define a class, it is also feasible to add a unified method by ourselves. Therefore, the above example can also be implemented like this:
/** * PHP多态性 */ // 定义学生类 class student{ // 定义统一的方法pub public function pub(){ echo "学生工正在上课!<br />"; } } // 定义职员类 class office{ // 定义统一的方法pub public function pub(){ echo "职员正在上班!<br />"; } } // 判断对象类型方法 function doing($obj){ if($obj){ // 调用类的统一方法 $obj->pub(); }else{ echo '没有这个对象'; } } doing(new student()); // 学生正在上课 doing(new office()); // 职员正在上班
Polymorphism can also be understood as a programming method, and the ultimate goal of programming is nothing more than: flexibility, polymorphism, reuse, and efficiency.
The above is the detailed content of What is polymorphism? PHP object-oriented polymorphism example tutorial. For more information, please follow other related articles on the PHP Chinese website!