Table of Contents
Introduction
抽象/Abstraction
抽象类/Abstract Class
接口/Interface
抽象类vs接口
Summary
Home Backend Development PHP Tutorial PHP设计模式(二):抽象类和接口

PHP设计模式(二):抽象类和接口

Jun 23, 2016 pm 01:12 PM

原文地址: PHP设计模式(二):抽象类和接口

Introduction

对于编程来说,对事物的抽象是一个老生常谈的话题,抽象问题更利于面向对象编程以及程序设计模式。和C/C++,Java,Python等语言一样,PHP也支持面向对象,但是又有略微区别,如PHP支持在接口中定义常量,但是不支持抽象变量。

抽象/Abstraction

对事物的抽象是指,区别两个不同事物之间的本质特征,这两个事物应该在某个视角上有明确的区分界限。

如,鲸鱼和鲤鱼,这两个事物在动物的视角上,有明确的区分界限,属于不同的动物;但是在水生动物的视角上,他们属于同一种动物的抽象。

合理的对问题进行抽象,构造模型,将更容易通过编程来解决问题。

记住:抽象是编程解决问题的基础,越复杂的问题,越需要一开始就对问题进行抽象,而不是直接写代码。

抽象类/Abstract Class

抽象类是一个编程概念,PHP中叫Abstract Classes。在设计模式中,抽象类不能够被实例化/初始化,但是可以依靠具体类的继承来实现。有点抽象,对吧?用代码来解释:

1

<?phpabstract class Animal {  public $nameabstract public function eat($food);}?>

Copy after login

定义了动物这个抽象类,动物的属性是名字name,然后有一个方法是吃食物eat food。

为什么动物是抽象类?因为动物这个物种并不是一个存在于自然界的东西,它是人类脑海里抽象出的东西。存在自然界的是鲸鱼和鲤鱼这样的确定性动物。

比如鲸鱼的概念,应该是属于动物,继承Animal类,我们定义鲸鱼这个类以及吃东西的方法:

1

<?phpclass Whale extends Animal {  public function __construct() {    $this->name = "Whale";  }  public function eat($food) {    echo $this->name . " eat " . $food . ".\n";  }}?>

Copy after login

现在我们可以初始鲸鱼类,并且调用吃的方法了:

1

<?php  $whale = new Whale();  $whale->eat("fish");?>

Copy after login
Copy after login

运行一下:

1

$ php Whale.phpWhale eat fish.

Copy after login
Copy after login

接口/Interface

PHP也支持面向过程编程概念中的接口,下面同样用鲸鱼的例子来讲述:

1

<?phpinterface IAction {  public function eat($food);  public function swim();}?>

Copy after login

同样定义一个鲸鱼类,来实现上述接口:

1

<?phpclass Whale implements IAction {  public function eat($food) {    echo "Whale eat " . $food . "\n.";  }  public swim() {    echo "Whale is swimming.\n";  }}?>

Copy after login

现在我们可以初始鲸鱼类,并且调用吃的方法了:

1

<?php  $whale = new Whale();  $whale->eat("fish");?>

Copy after login
Copy after login

运行一下:

1

$ php Whale.phpWhale eat fish.

Copy after login
Copy after login

抽象类vs接口

上面的抽象类和接口的例子,看上去是不是类似?事实上,对于PHP编程来说,抽象类可以实现的功能,接口也可以实现。

抽象类的接口的区别,不在于编程实现,而在于程序设计模式的不同。

一般来讲,抽象用于不同的事物,而接口用于事物的行为。

如:水生生物是鲸鱼的抽象概念,但是水生生物并不是鲸鱼的行为,吃东西才是鲸鱼的行为。

对于大型项目来说,对象都是由基本的抽象类继承实现,而这些类的方法通常都由接口来定义。

此外,对于事物属性的更改,建议使用接口,而不是直接赋值或者别的方式,如:

1

<?phpinterface IAction {  public function eat();}class Whale implements IAction {  public function eat() {    echo "Whale eat fish.\n";  }}class Carp implements IAction {  public function eat() {    echo "Carp eat moss.\n";  }}class Observer {  public function __construct() {    $whale = new Whale();    $carp = new Carp();    $this->observeEat($whale);    $this->observeEat($carp);  }  function observeEat(IAction $animal) {    $animal->eat();  }}$observer = new observer();?>

Copy after login

运行一下:

1

$ php Observer.phpWhale eat fish.Carp eat moss.

Copy after login

Summary

好的设计模式是严格对问题进行抽象,虽然抽象类和接口对于编程实现来说是类似的,但是对于程序设计模式是不同的。

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

Video Face Swap

Video Face Swap

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

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)

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles