PHP类的使用 实例代码讲解_php技巧
PHP 只有类别 (class)、方法 (method)、属性、以及单一继承 (extensions) 等。对不习惯使用 C++、Java、Delphi 等面向对象语言来开发程序的用户,不妨先阅读一下有关面向对象概念的书,相信可以带来许多的收获。
下面的范例是手推车类。可以看到,使用 class 表示它是一个类类别。在类别中的 function,例如 add_item 则表示该类的一个方法。方法可以封装类的实际处理情形,让该类自己能依封装好的方法来执行一些步骤。
程序中的 $this 类变量也和 $GLOBALS 及 $php_errormsg 两个变量一样,在 PHP 中属于特殊的变量。$this 变量只用在类类别中,表示类的本身。
// 程序名: cart.inc
class Cart {
var $items; // 手推车类
// 本方法加入 $num 件物品到手推车中 (加到 $artnr 变量)
function add_item ($artnr, $num) {
$this->items[$artnr] += $num;
}
// 本方法从手推车减少 $num 件物品 (从 $artnr 变量减掉)
function remove_item ($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} else {
return false;
}
}
}
?>
要使用手推车可以用类似下例的方式。可以先将每个类存成 Include 文件,再将它 require 或 include 进来。在定义变量 $cart 时,要使用 new 的保留字,表示 $cart 使用 Cart 类。使用 -> 符号,表示执行类的方法。
require("cart.inc");
$cart = new Cart;
$cart->add_item("10", 1);
?>
之后再设计有记名的手推车。记名手推车从手推车遗传下来,因此手推车拥有的方法及属性,记名手推车也有,而记名手推车比手推车增加了名字的方法 (或许该称属性较恰当)。
从下例中可以看到,子类 Named_Cart 使用 extends 来继承其父类 Cart。虽然 Named_Cart 类中没有增加物品及减少物品的方法,不过由于遗传的特性,父类有的东西它都有。
// 程序名: named_cart.inc
require("cart.inc");
class Named_Cart extends Cart {
var $owner;
function set_owner ($name) {
$this->owner = $name;
}
}
?>
要使用记名手推车类,请看下面的范例。当然这不算太好的设计,每个子类都一直 require 它的父类,会造成服务器在 I/O 上面的负担。在实作时,可以将整个系列的类在同一个程序文件中,从最早的袓先类到最后的子孙类,也方便日后修正。
require("named_cart.inc");
$ncart = new Named_Cart; // 建立类变量
$ncart->set_owner ("CyberRidder"); // 配置类的记名属性
echo $ncart->owner; // 显示类的记名属性
$ncart->add_item ("10", 1); // 从父类遗传的方法也可使用
?>
因此,在 PHP 中使用了 extends 保留字,加上良好的系统分析与完整的 CRC 卡片 (详见面向对象相关书籍) 设计之后,PHP 可变成拥有强大类能力的 CGI 语言。
PHP 由于是脚本语言 (Script),因此程序源代码可见,在软件工程中的元件黑箱并不会在目前的 PHP 版本中出现,也就是说,全部的类其实没有隐藏起它的内容。对于软件业者而言,没有办法保护所谓的软件 IC,站在开放团体而言,反而有源代码是件好事,至于孰是孰非,就很难判定了,不过目前 PHP 还是 Open Source 团体的一份子,或许日后 Zend 引擎可以做到类封装的功能也不一定。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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,

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

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

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