Table of Contents
Objectives of this article:
(1) Understand the definition of abstract classes in PHP (What)
(2) Understand the role of abstract classes in PHP (Why)
(3) Understand the usage scenarios of abstract classes in PHP (Where)
(4) Master the specific implementation of abstract classes in PHP (How)
(5), specific code
(六)、学以致用
(7), Summary
Home Backend Development PHP Tutorial Detailed explanation of PHP object-oriented abstract classes (code examples)

Detailed explanation of PHP object-oriented abstract classes (code examples)

May 27, 2020 pm 03:54 PM
object-oriented

Objectives of this article:

1. Understand the definition of abstract classes in PHP

2. Understand the role of abstract classes in PHP

3. Understand the functions of abstract classes in PHP Usage scenarios

4. Master the specific implementation of abstract classes in PHP

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

(1) Understand the definition of abstract classes in PHP (What)

Abstract classes are often used to characterize the analysis and design of problem areas. Abstract Concept is an Abstract for a series of specific concepts that look different but are essentially the same. Classes usually modified with abstract in programming statements are Abstract classes.

#The difference between the interface and the interface is that the methods in the interface are not implemented, but are simply defined, but the methods in the abstract class can be implemented of.

(2) Understand the role of abstract classes in PHP (Why)

Among the classes in PHP, many classes will be constantly rewritten. This Sometimes we can use abstract classes, how to do it? That is to write a public class first, and then we can call it repeatedly after instantiating it. This can improve the reusability of the code

(3) Understand the usage scenarios of abstract classes in PHP (Where)

1. If you find that many classes in the code are similar or Common methods, we can extract these same or similar methods and encapsulate them into abstract classes.

Abstract classes and interfaces are somewhat similar. It can be said that the interface is a special abstract class, but the interface is full of abstract methods (the so-called abstract means that there is no specific implementation), but in the abstract class Some methods can have implemented functions,

(4) Master the specific implementation of abstract classes in PHP (How)

Summary:

1. Abstract classes The definition is defined through abstract, such as abstract class class name {}

2. The definition of the method of the abstract class is also defined through abstract, such as abstract public function method name (){}

3. Abstract Classes cannot be instantiated

4. To inherit an abstract class, use the keyword extends

5. Subclasses of abstract classes must implement things that are not implemented in the abstract class. All methods, that is to say, rewrite all abstract methods in the abstract class

6. Although the subclasses of the abstract class do not implement the methods that have been implemented in the abstract class, they can still call these methods. In fact, combined with inheritance We can understand this very well

Every summary is obtained through practice. Now we use practice to demonstrate the summary, which can promote understanding and make each summary more understandable. Clear and intuitive

(5), specific code

Case 1,

Practice goals:

1. The definition of an abstract class is defined by abstract, such as abstract class class name {}

2. The definition of an abstract class method is also defined by abstract, such as abstract public function method name (){}

The specific code is as follows:

<?php
abstract class Animal{
    abstract public function eat();//抽象方法
    //呼吸
    public function breath(){
        //所有动物的呼吸方法都是一样的,就不需要使用多态了
        echo "呼吸<br/>";
    }
}
?>
Copy after login

Case 2,

Practical goals:

1. Abstract classes cannot be instantiated The specific code of

is as follows:

<?php
abstract class Animal{
    abstract public function eat();//抽象方法
    //呼吸
    public function breath(){
        //所有动物的呼吸方法都是一样的,就不需要使用多态了
        echo "呼吸<br/>";
    }
}
$animal = new Animal();
?>
Copy after login

The running result is:

Fatal error: Uncaught Error: Cannot instantiate abstract class Animal in D:\E-class\class-code\classing\index.php:10 Stack trace: #0 {main} thrown in D:\E-class\class-code\classing\index.php on line 10

案例四、

实践目标:

1、要继承一个抽象类,通过关键字extends

2、抽象类的子类必须要实现抽象类中未实现的所有方法,也就是说要重写抽象类中所有abstract的方法

具体代码如下:

<?php
abstract class Animal{
    abstract public function eat();//抽象方法
    //呼吸
    public function breath(){
        //所有动物的呼吸方法都是一样的,就不需要使用多态了
        echo "呼吸<br/>";
    }
}
//定义猴子
class Monkey extends Animal{
    
}
?>
Copy after login

如果Monkey类继承了抽象类,但不实现里面的abstract方法,那么运行结果为:

Fatal error: Class Monkey contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Animal::eat) in D:\E-class\class-code\classing\index.php on line 13

接下来我们来实现abstract方法

具体代码如下:

<?php
abstract class Animal{
    abstract public function eat();//抽象方法
    //呼吸
    public function breath(){
        //所有动物的呼吸方法都是一样的,就不需要使用多态了
        echo "呼吸<br/>";
    }
}
//定义猴子
class Monkey extends Animal{
    //实现抽象类中的抽象方法
    public function eat(){
        echo "我是猴子类中的eat方法<br/>";
    }
}
$monkey = new Monkey();
$monkey->eat();

?>
Copy after login

运行结果如下:

我是猴子类中的eat方法

案例五、

实践目标:

1、抽象类的子类虽然没有实现抽象类中的已经实现的方法,一样可以调用这些方法,其实结合继承我们可以很好理解这点

具体代码如下:

<?php
abstract class Animal{
    abstract public function eat();//抽象方法
    //呼吸
    public function breath(){
        //所有动物的呼吸方法都是一样的,就不需要使用多态了
        echo "抽象类中的呼吸方法<br/>";
    }
}
//定义猴子
class Monkey extends Animal{
    //实现抽象类中的抽象方法
    public function eat(){
        echo "我是猴子类中的eat<br/>";
    }
}
$monkey = new Monkey();
$monkey->eat();
$monkey->breath();
?>
Copy after login

运行结果如下:

我是猴子类中的eat
抽象类中的呼吸方法

(六)、学以致用

问题:将以下真实场景,用抽象类还原出来

小芳放学回到家中,一进家门,只见心爱的小狗“小爱”马上就对主人摇起了尾巴,小芳笑了笑,走过去,抱起了小狗,最后,小芳和小狗亲了一口

思路分析:

1、对象分析:学生,小狗

2、对象属性分析:结合(现实世界+具体场景)

学生:名称

狗:名称

3、对象方法分析:结合(现实世界+具体场景)

学生:

(1)、放学

(2)、回到家中

(3)、走路

(4)、看

(5)、笑

(6)、抱东西

(7)、亲嘴

狗:

(1)、看

(2)、摇尾巴

(3)、亲嘴

4、我们发现这2个对象都有相似的方法,看,亲嘴,所以我们可以把它们封装到抽象类中,并且这2个方法不需要子类去重写,因为都是一样的

具体代码如下:

<?php
abstract class Animal{
    //看
    public function look($obj){
        //所有动物的呼吸方法都是一样的,就不需要使用多态了
        echo "看见了".$obj->name."<br/>";
    }
    //亲嘴
    public function kiss($fromobj,$toobj){
        echo $fromobj->name."亲了".$toobj->name."一口<br/>";
    }
    
}
//学生
class Student extends Animal{
   public $name = "";
   public function __construct( $name ){
       $this->name = $name;
   }
    // 1、放学
   public function offschool(){
       echo $this->name."放学了<br/>";
   }
   //回家
   public function goHome(){
    echo $this->name."回到家中<br/>";
   }
    // 2、走路
    public function walk(){
        echo $this->name."走了过去<br/>";
    }
    // 3、看

    // 4、笑
    public function smile(){
        echo $this->name."微笑了<br/>";
    }
    // 5、抱东西
    public function hug($obj){
        echo $this->name."抱起了".$obj->name."<br/>";
    }
    // 6、亲嘴
   
}
//狗
class Dog extends Animal{
   public $name = "";
   public function __construct( $name ){
       $this->name = $name;
   }
    //1、看

    //2、摇尾巴
    public function wagTail(){
        echo $this->name."摇了尾巴<br/>";
    }

    //3、亲嘴
}
//创建对象
$xf = new Student("小芳");
$dog = new Dog("小爱");
//小芳放学了
$xf->offschool();
//小芳放学回到家中,一进家门,只见心爱的小狗“小爱”马上就对主人摇起了尾巴,小芳笑了笑,走过去,
//抱起了小狗,最后,小芳和小狗亲了一口
//小芳回答家中
$xf->goHome();
//小芳看见小狗
$xf->look($dog);
//小狗摇尾巴
$dog->wagTail();
//小芳笑了笑
$xf->smile();
//小芳走过去
$xf->walk();
//抱起小狗
$xf->hug($dog);
//小芳亲了小狗
$xf->kiss($xf,$dog);
//小狗也亲了小芳
$dog->kiss($dog,$xf);
?>
Copy after login

运行结果为:

Xiaofang is after school
Xiaofang returns home
I see Xiao Ai
小Ai wagged her tail
Xiaofang smiled
Xiaofang walked over
Xiaofang hugged Xiaoai
Xiao Fang kissed Xiao Ai
Xiao Ai kissed Xiao Fang

(7), Summary

1. This article mainly explains the definition, function and specific implementation of abstract classes in PHP

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

The above is the detailed content of Detailed explanation of PHP object-oriented abstract classes (code examples). 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