Table of Contents
Objectives of this article:
(1) Understand polymorphism Definition
(2), understand polymorphism The function
(3) Understand the usage scenarios of polymorphism
(4), master the specific implementation of polymorphism
(5), specific code
(6) Apply what you learn
Home Backend Development PHP Tutorial Detailed explanation of PHP object-oriented polymorphism (code example)

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

May 26, 2020 pm 03:46 PM
object-oriented

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);
?>
Copy after login

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);//给小狗喂食

?>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement object-oriented event-driven programming using Go language How to implement object-oriented event-driven programming using Go language Jul 20, 2023 pm 10:36 PM

How to use Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

What is the importance of @JsonIdentityInfo annotation using Jackson in Java? What is the importance of @JsonIdentityInfo annotation using Jackson in Java? Sep 23, 2023 am 09:37 AM

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Aug 14, 2023 pm 05:25 PM

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming Jun 05, 2024 pm 08:50 PM

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

See all articles