search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP object-oriented abstract classes (code examples)

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/>";
    }
}
?>

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();
?>

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{
    
}
?>

如果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();

?>

运行结果如下:

我是猴子类中的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();
?>

运行结果如下:

我是猴子类中的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);
?>

运行结果为:

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)