Home php教程 php手册 PHP V5.3 用延后静态绑定搞活面向对象编程

PHP V5.3 用延后静态绑定搞活面向对象编程

Jun 21, 2016 am 08:54 AM
php

PHP V5.3 通过其延后静态绑定(LSB)特性解决了面向对象编程(OOP)的一些问题。了解 LSB 如何修复 PHP 的 OOP 编程问题以及如何实现需要使用 LSB 的一些众所周知的面向对象设计模式。
面向对象编程(OOP)可让开发人员通过使用数据抽象、封装、模块化、多态性和继承减少和简化代码 — 在对 OOP 有着深刻的理解的前提下。对 OOP 特性的了解还让 PHP 编码者得以利用设计模式 — 一些众所周知的用来解决常见问题的算法。PHP 自 V3.0 就已经提供了 OOP 功能,但直到 V5.3 到来时,PHP 的 OOP 实现内的怪异之处还是会阻止一些常见设计模式的使用。随着 PHP V5.3 的延后静态绑定(LSB)特性的出现,这些怪异之处均已彻底消失。

本文向您介绍了在 PHP V5.3 出现之前,存在问题的一些设计模式,解释了这些模式为何不能工作。然后展示了 PHP V5.3 的 LSB 特性,并给出了单例和活动记录设计模式。

重新回顾 OOP

如果您过去曾接触过 PHP OOP,那么很可能会出于以下原因而决定不使用它:

读过诸多宣称 PHP OOP 有问题的博文中的一条。

曾尝试实现一个简单的设计模式,但没有成功。

而对于 PHP V5.3,有关 OOP 的博文都是正面的,并且 PHP OOP 的问题在很大程度上已得到解决。是时候重回 PHP OOP 了。通过本文,您将看到在 V5.3 出现之前曾存在问题的一些设计模式:单例、生成器、工厂方法和活动记录。

单例、生成器和工厂方法设计模式被视为是 创建型 的模式,因它们可协助对象的构建。单例模式可能是最常用的 OOP 设计模式之一了 ;它限制了一个类的对象实例数只能为 1。比如数据库连接池就是单例设计模式的一个例子:我们一般不想让应用程序具有连接池类的多个资源密集型实例。

在需要分离复杂对象的构建和表示时,就需要用到生成器设计模式,您可以使用相同的构造过程来创建多个对象。生成器模式的实现可以很复杂,但一旦生成器可用,它就可以简化生成器所创建对象的构造和使用。具有输出 HTML、XML 或 PDF 能力的转变器就是需要使用生成器的一个例子。

而工厂方法模式,顾名思义,定义的是一个用来大量产出对象的方法的实现。您可以在应用程序需要创建其类型依赖于子类的实现的对象时,使用工厂方法模式。

活动记录模式则可用来在域类内包装关系数据库持久性方法。一个活动记录的每个实例都关系到数据库内的特定行。这个类包含了要插入、删除和更新数据库内的一行或多个行的方法。活动记录设计模式是由 Martin Fowler 在 Patterns of Enterprise Application Architecture 内定义的,并因在 Ruby on Rails 内的使用而日益流行。

前-LSB 的创建型设计模式实现问题

上述提到的所有这四个设计模式均使用了静态的属性和方法。例如,看一下清单 1 内所示的这个连接池单例。

清单 1. 一个简单的单例

class ConnPool {
private static $onlyOne;
private static $count = 0;
private function __construct() {
// real-world db conn stuff here...
}

public static function getInstance() {
if (!is_object(self::$onlyOne)) {
$klass = __CLASS__;
self::$onlyOne = new $klass();
self::$count++;
}
return self::$onlyOne;
}
public static function getInstanceCount() {return self::$count;}
}

$db = ConnPool::getInstance();
assert (1 == $db->getInstanceCount());
$db2 = ConnPool::getInstance();
assert (1 == $db2->getInstanceCount());
?>
请注意这个静态的 $onlyOne 变量。该变量被设计用来保存连接池对象的一个实例。$onlyOne 之前的静态修饰符将此变量关系到类本身。$onlyOne 变量是一个类属性,因为其作用域是这个类。而 $onlyOne 属性只有一个实例。当一个属性不具有静态修饰符时,就称其是一个对象属性,因为该属性对类的每个实例都是惟一的。

注意到 ConnPool 的构造函数方法(called __construct)是空的。在一个生产实现中,可以使用该方法来创建数据库连接池的间隔。

静态 getInstance 方法包含单例的模板代码。只有在静态的 $onlyOne 变量为空时,它才会创建一个 $onlyOne 实例。请注意它是如何使用 __CLASS__ 变量来获得类的类型并随即创建该类的一个实例的。

使用 getInstanceCount 方法只是为了证明只创建了连接池的一个实例。清单 1 底部的四行代码则证明无论请求 ConnPool 池类的一个实例多少次,它都会返回相同的对象。

所以, 到目前为止,此单例一切正常 — 直到您决定想要以面向对象的继承树的形式对这个连接池进行子类处理来支持多个数据库。清单 2 显示了这个继承树(为了清晰起见,删除了实例计数器和构造函数代码)。

清单 2. 在没有 LSB 时对单例进行的一次失败尝试

class ConnPool {
private static $onlyOne;
protected static $klass = __CLASS__;

public static function getInstance() {
if (!is_object(self::$onlyOne)) {
self::$onlyOne = new self::$klass();
}
return self::$onlyOne;
}
}

class ConnPoolAS400 extends ConnPool {
protected static $klass = __CLASS__;
}
$db = ConnPoolAS400::getInstance();
assert ('ConnPoolAS400' == get_class($db)); // fails
?>
为了支持多个类型的单例类,ConnPool 类添加了一个 $klass 静态变量并假设它会在子类中被覆盖。 ConnPoolAS400 子类扩展了 ConnPool 类并提供了 $klass 属性自己的版本。 我们的预期是当 ConnPoolAS400 类的实例创建时,$klass 属性会保存 ConnPoolAS400。但是当执行这些代码时,它不会按预期的那样运行。当 PHP 实用函数 get_class 返回 ConnPool 而不是 ConnPoolAS400 时,代码底部的声明会失败。 问题是 ConnPool 类的 getInstance 方法使用的是它自己的 $klass 属性版而非 ConnPoolAS400 的覆盖版。




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)

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

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 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

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

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 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