Table of Contents
Objectives of this article:
(2) Benefits of inheritance
Home Backend Development PHP Tutorial Object-oriented inheritance in PHP

Object-oriented inheritance in PHP

May 24, 2020 pm 03:52 PM
php object-oriented

Objectives of this article:

1. Understand the definition of inheritance

2. Master the benefits of inheritance

(1).Definition

    Object-oriented inheritance in PHP

Let’s look at the picture above carefully, and then do one thing to find out what they have in common

Common ground:

1. They all have some of the same attributes and methods

2. They are all human beings

Follow the definition of normal classes. If we want to implement the above two classes, we have to define them separately. All attributes and methods of the NBA player class, and then when defining the female anchor class, you have to write repeated attributes such as name, height, weight and eating methods. If there is another class called student, it means that these common The attributes and common methods have to be written again, and so on. The code will be similar in many places, which increases the redundancy of the code. Therefore, in order to solve this redundancy, in order to make the code more concise and reusable High, we can write these common attributes and methods together, and then let each class call this common attribute and method. Will it be more convenient to maintain and the code will be more concise? Then We call this approach inheritance

How to do it specifically, as shown below

Object-oriented inheritance in PHP

We first create a "person" class, let this person Both have attributes and methods common to both classes, and then let both NBA players and female anchors inherit the "person" class

Object-oriented inheritance in PHP

Concept: The inherited class is called the parent class, such as people, and the inherited class is called the subclass

Summary: What is inheritance? Inheritance is a method to improve the reusability of code and reduce the number of The redundancy of code is just like heredity in real life. Children will inherit part of their parents’ genes, so when you are born, you will have the common attributes and behaviors of humans

(2) Benefits of inheritance

1. Improve code reusability and save programming time and cost

The attributes and methods defined in the parent class do not require subclasses If the definition is repeated in a class, as long as the subclass inherits the parent class, it will have all the properties and methods in the parent class

2. All subclasses under the same parent class can be treated equally when calling them

For example, whether it is an NBA player or a female anchor, because they are all human beings, when we call them, we can directly call the method of the parent class, such as eating, regardless of whether the class is an NBA player or a female anchor

3. Subclasses can modify and adjust the class members defined by the parent class

a. We call it Overwrite

b. Once the subclass is modified, Execute according to the method defined by the subclass

This is equivalent to mutation

To learn anything, we must not only know the theory, but also have relevant theoretical practices. In fact, all theories are derived from practice. Yes, so sometimes I have repeatedly emphasized that although the theory is very abstract, everyone must also summarize it after they have certain practical experience, and summarize some concise and easy-to-understand "theory". After this habit is cultivated, I believe Everyone can understand a lot of knowledge more thoroughly, and at the same time, it is easier to grasp the essence of things, so that the ability to analyze problems will also be improved.

Okay, since we need to combine theory and practice, then next, we will conduct a practical demonstration through the code to see how inheritance is implemented in the code

( 3) Specific code

<?php
/***
 * 案例目标
 * 1.掌握继承的定义
   2.掌握继承的好处
 */
 //定义一个“人”类
class Human{
    public $name = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重

    public function eat($food){
        echo $this->name."在吃".$food."<br/>";
    }
}
//女主播
class Anchors extends Human{
    public $name = "";
    public $stageName = "";
    public function __construct( $name,$stageName ){
        $this->name = $name;
        $this->stageName = $stageName;
    }
    public function singing(){
        echo "我是女主播,我会唱歌<br/>";
    }
    //重写方法eat
    public function  eat($food){
        echo "我是女主播,我是边唱歌边吃{$food}<br/>";
    }
}
//Nba球员类
 class NbaPlayer extends Human{
   //因为父类已经有了,所以就不需要再写了,通过extends来实现
    // public $name  = "";//姓名
    // public $height = "";//身高
    // public $weight = "";//体重

    public $team = "";//团队
    public $playerName = "";//球员号码

    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }
    //重写方法eat ,只要名称和父类一样就是代表重写了不一定参数也要保持一样
    public function eat($food){
        echo "我是Nba球员,我是站着吃饭,边吃{$food}边看球赛<br/>";
    }
 }
 //测试,NBA球员,没有直接定义name,身高,体重,现在输出一下看结果有没有
 //创建乔丹对象
 $jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");
 //输出乔丹对象
 echo "名称= ".$jordon->name."<br/>";

 //测试,NBA球员,没有直接定义eat方法,现在输出一下看结果有没有
 echo $jordon->eat("苹果");
 //证明第二个好处,只要是个人就可以调用它的eat方法
 $linda = new Anchors("琳达","LD");
 echo $linda->eat("苹果");
 //测试第三个好处是否真实
 //思路1.为女主播和NBA球员2个类分别重写eat方法
//    2.再次执行2个对象的eat方法
//  会发现一旦子类重写了父类的方法,那么就会调用子类自己的方法了,这里就大家自己写下,因为上面我已经调用了eat方法,一旦重写了,上面的结果会变

?>
Copy after login

Through the demonstration of the above code, we summarize:

1. extends means inheritance. Through this keyword, the subclass can inherit the parent Class, sharing all attributes and methods of the parent class

2. Other features of inherited code:

● In the subclass constructor, it can also be accessed directly through $this->

● In PHP, only one class can be inherited after extends, and cannot be used to inherit multiple classes, otherwise an error will be reported

Summary:

This article In fact, there are only two goals. Knowing the definition and benefits of inheritance. Finally, we believe that we have a deeper understanding of the benefits of inheritance through code

The above is the detailed content of Object-oriented inheritance in PHP. 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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles