Home  >  Article  >  Backend Development  >  Detailed explanation of PHP object-oriented polymorphism (code example)

Detailed explanation of PHP object-oriented polymorphism (code example)

易达
易达Original
2020-05-26 15:46:492556browse

Objectives of this article:

1. Understand the definition of polymorphism

2. Understand the role of polymorphism

3. Understand the usage scenarios of polymorphism

4. Master the specific implementation of polymorphism

Still following the previous consistent thinking, we learn through the 3W1H method, so first let’s learn about it

(1) Understand polymorphism Definition

Because there can be many method implementations in the interface, the specific implementations of the methods defined in the interface are diverse. This feature is called "Polymorphism"

-For example, interface A has two implementations, B and C. B and C can have different methods defined in A. This phenomenon is polymorphism

(2), understand polymorphism The function

The function is to allow an interface to have different implementations, so that the code is more consistent with the real world. This method shortens the distance between the code and the real world, so that developers can be more Conveniently implement some complex business logic in the implementation

(3) Understand the usage scenarios of polymorphism

In fact, this usage scenario, once we decide to use an interface, this The phenomenon will appear, because once an interface has different implementation classes, this phenomenon will basically happen, because many times we hope that one or more methods in an interface can have different specific implementations

-For example, every animal has its own way of eating. Rats and cats eat directly and don’t think about hygiene, so they don’t wash the food before eating. But humans are advanced animals, so they pay attention to basic hygiene (except for the mentally ill), wash themselves before eating, and judge that some things must be cooked before eating. And because of cultural differences, each country People also eat in different ways. For example, Indians eat directly with their hands, while Chinese eat with chopsticks, and some Western countries use forks. There are different ways of eating, which is very common in real life. The same is true for many other things, so the phenomenon of polymorphism is also very common, and we write code using object-oriented programming, so it is inevitable that we will also encounter "polymorphism", and in order to make our To make the code more relevant to the real world, we must also use "polymorphism"

(4), master the specific implementation of polymorphism

Summary:

1. The definition of polymorphism is that each interface can have multiple different implementations

Each summary is derived through practice. Now we use practice to demonstrate the summary, which can promote understanding and make each summary understandable. It becomes clearer and more intuitive

(5), specific code

1, Case 1

Practical goals:

1. The definition of polymorphism is that each interface can have multiple different implementations

<?php
//定义吃的接口
interface Eat{
    public function eat();
}
//定义猫的类
class Cat implements Eat{
    public function eat(){
        echo "我是猫,抓到喜欢的老鼠,直接吃<br/>";
    }
}
//定义人
class Human implements Eat{
    public function eat(){
        echo "我是人,吃东西之前,都会洗一下再吃,因为我要讲究基本的卫生<br/>";
    }
}

function Eat( $obj ){
    if( $obj instanceof Eat ){
        $obj->eat();
    }else{
        echo "该对象没有实现Eat的方法<br/>";
    }
}
$cat = new Cat();
$zs = new Human();
//这行代码看出,一个吃的方法,传递不同的具体实现,结果就是可以有不同的实现,这就是多态
Eat($cat);
Eat($zs);
?>

The running result is:

I am a cat. If I catch the mouse I like, I will eat it directly
I am a human being. I wash myself before eating because I have to pay attention to basic hygiene

(6) Apply what you learn

Question: Using object-oriented programming The method simulates the following real scene, and the code must reflect the concept of polymorphism

A rural old man, Xiao Liu, raised 5 chickens and 5 dogs. Every morning, he would be on time at 6 o'clock Get up, cook porridge, and after eating porridge, he will carry 2 small buckets of food to feed the chickens and ducks, walk to the chicken pen, and pour one of the buckets of rice into the chicken trough, and then walk to the doghouse Next to it, he poured the remaining bucket of food with leftovers into the dog’s trough

Idea analysis:

1. Object analysis: The objects inside are Old man, chicken, dog, food, so there are at least these 4 categories

2. Object attribute analysis: (Combined with the specific scene in the real world)

Old man: Name

Chickens: Number

Dogs: Number

Food: Name

3. Object method analysis: (Combined with the specific scene of the real world)

Old man: get up, cook porridge, eat (eat porridge), feed

Chicken: eat (pecking rice to eat)

Dog: eat (eat bones)

Food: Set the food name

4. Based on the above analysis, we found that three of the objects have ways to eat, but they have different ways of eating, so we can extract this public method Separate it and make an interface, and then let these three classes implement it respectively

The specific implementation code is as follows:

<?php
//定义吃的接口
interface Eat{
    public function eat($food);
}
//定义食物
class Food{
    public $name = "";
    public function __construct( $name ){
        $this->name = $name;
    }
}

//定义人
class Human implements Eat{
    public $name = "";
    public function __construct( $name ){
        $this->name = $name;
    }
    //起床
    public function wakeup(){
        echo $this->name."起床了<br/>";
    }
    //煮稀饭
    public function cook($food){
        echo $this->name."煮".$food->name."了<br/>";
    }
    public function eat($food){
        echo $this->name."吃了".$food->name."<br/>";
    }
    //喂食
    function startFeed( $obj,$food ){
        if( $obj instanceof Eat ){
            $obj->eat($food);
        }else{
            echo "该对象没有实现Eat的方法<br/>";
        }
    }

    public function feed($obj, $food){
        $this->startFeed( $obj,$food );
    }
}
//定义鸡的类
class Chiken implements Eat{
    public $count = 5;
    public function eat($food){
        echo $this->count."只小鸡们,都吃了".$food->name."<br/>";
    }
}
//定义狗的类
class Dog implements Eat{
    public $count = 5;
    public function eat($food){
        echo $this->count."只小狗们,都吃了".$food->name."<br/>";
    }
}

//创建对象
$xiaoliu = new Human("小刘");
$chikens = new Chiken();
$dogs = new Dog();
//创建食物
$xfFood = new Food("稀饭");
$seedsFood = new Food("米");
$mealFood = new Food("残羹剩饭");
//老人起床
$xiaoliu->wakeup();
//老人煮稀饭
$xiaoliu->cook($xfFood);
//老人吃稀饭
$xiaoliu->eat( $xfFood );
//老人喂食开始
$xiaoliu->feed($chikens,$seedsFood);//给小鸡喂食
$xiaoliu->feed($dogs,$mealFood);//给小狗喂食

?>

The running result is:

小流Get Up
小六cooked the porridge
xiao liu ate the porridge
The 5 chickens all ate the rice
The 5 puppies all ate the leftovers

(7) Summary

1. This article mainly talks about the definition and function of polymorphism, as well as the specific implementation

I hope this article can bring you some help, thank you! ! !

The above is the detailed content of Detailed explanation of PHP object-oriented polymorphism (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn