PHP编程完全指南
一、PHP概述
1.1 语言简介
PHP(Hypertext Preprocessor)是一种开源的通用脚本语言,尤其适用于Web开发并可嵌入HTML中。最初由Rasmus Lerdorf于1994年创建,现在由PHP Group维护。
核心特性:
| 特性 | 说明 |
|---|---|
| 服务器端执行 | 在服务器上运行,生成HTML发送给客户端 |
| 跨平台 | 支持Windows、Linux、macOS、Unix等操作系统 |
| 嵌入HTML | 可直接嵌入HTML代码中,使用<?php ?>标签 |
| 弱类型 | 变量类型由上下文自动确定,支持类型转换 |
| 丰富扩展 | 内置大量函数库,支持数据库、图形、加密等 |
| 开源免费 | 完全开源,社区活跃,生态丰富 |
| 高性能 | PHP 7+性能大幅提升,PHP 8引入JIT编译 |
| 广泛支持 | 几乎所有主机商都支持PHP,部署简单 |
1.2 PHP版本历史
| 版本 | 发布时间 | 主要特性 |
|---|---|---|
| PHP 1.0 | 1995年 | 最初版本,Personal Home Page Tools |
| PHP 3.0 | 1998年 | 重写内核,支持扩展API |
| PHP 4.0 | 2000年 | Zend引擎,支持会话、输出缓冲 |
| PHP 5.0 | 2004年 | 全新面向对象模型、PDO、SimpleXML、异常处理 |
| PHP 5.3 | 2009年 | 命名空间、闭包、goto、后期静态绑定 |
| PHP 5.4 | 2012年 | Traits、短数组语法、内置Web服务器 |
| PHP 5.5 | 2013年 | 生成器、finally块、密码哈希API |
| PHP 5.6 | 2014年 | 可变参数函数、参数解包、常量表达式 |
| PHP 7.0 | 2015年 | 性能翻倍、标量类型声明、返回类型声明、空合并运算符、匿名类 |
| PHP 7.1 | 2016年 | 可空类型、void返回类型、类常量可见性、多异常捕获 |
| PHP 7.2 | 2017年 | object类型、参数类型加宽、Argon2密码哈希 |
| PHP 7.3 | 2018年 | 灵活的Heredoc/Nowdoc、数组解构、is_countable |
| PHP 7.4 | 2019年 | 类型属性、箭头函数、空合并赋值运算符、预加载 |
| PHP 8.0 | 2020年 | JIT编译、联合类型、match表达式、命名参数、构造器属性提升、Nullsafe运算符 |
| PHP 8.1 | 2021年 | 枚举、Fiber、readonly属性、纯交集类型、never返回类型 |
| PHP 8.2 | 2022年 | readonly类、独立类型、敏感参数值、动态属性废弃 |
| PHP 8.3 | 2023年 | 类型化类常量、动态获取类常量、json_validate、新增随机方法 |
1.3 应用场景
CODE
┌─────────────────────────────────────────────────────────────────────┐
│ PHP 应用场景 │
├───────────────────┬───────────────────┬─────────────────────────────┤
│ Web开发 │ 内容管理 │ 电子商务 │
│ │ │ │
│ • 动态网站 │ • WordPress │ • WooCommerce │
│ • Web应用 │ • Drupal │ • Magento │
│ • RESTful API │ • Joomla │ • OpenCart │
│ • 微服务 │ • Typo3 │ • PrestaShop │
├───────────────────┼───────────────────┼─────────────────────────────┤
│ 框架开发 │ 命令行工具 │ 数据处理 │
│ │ │ │
│ • Laravel │ • 脚本自动化 │ • 数据导入导出 │
│ • Symfony │ • 定时任务 │ • 日志分析 │
│ • CodeIgniter │ • 系统管理 │ • 报表生成 │
│ • Yii │ • 测试工具 │ • ETL流程 │
└───────────────────┴───────────────────┴─────────────────────────────┘
1.4 环境搭建
BASH
# ========== Linux (Ubuntu/Debian) 安装 ==========
sudo apt update
sudo apt install php8.2 php8.2-cli php8.2-fpm php8.2-mysql \
php8.2-curl php8.2-mbstring php8.2-xml php8.2-zip \
php8.2-gd php8.2-bcmath php8.2-json
# 验证安装
php -v
# PHP 8.2.x (cli) ...
# ========== macOS 安装 (Homebrew) ==========
brew install php@8.2
# ========== Windows 安装 ==========
# 下载 XAMPP 或 WAMP 集成环境
# 或从 https://windows.php.net/download 下载
# ========== Composer 安装(包管理器)==========
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
sudo mv composer.phar /usr/local/bin/composer
# 验证 Composer
composer --version
PHP
<?php
// ========== 第一个PHP程序 ==========
// 保存为 hello.php,运行: php hello.php
echo "Hello, World!\n";
// ========== PHP配置信息 ==========
// 运行: php -i 或访问 phpinfo()
phpinfo();
// ========== 内嵌Web服务器 ==========
// 运行: php -S localhost:8000
// 访问: http://localhost:8000
?>
1.5 PHP标记与HTML嵌入
PHP
<?php
// ========== PHP标记风格 ==========
// 标准标记(推荐)
echo "标准PHP标记\n";
// 短标记(需开启 short_open_tag)
// <? echo "短标记\n"; ?>
// ========== HTML嵌入 ==========
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP嵌入HTML示例</title>
</head>
<body>
<h1>当前时间: <?php echo date("Y-m-d H:i:s"); ?></h1>
<?php if (date("H") < 12): ?>
<p>早上好!</p>
<?php elseif (date("H") < 18): ?>
<p>下午好!</p>
<?php else: ?>
<p>晚上好!</p>
<?php endif; ?>
</body>
</html>
<?php
// ========== 纯PHP文件(不闭合标记)==========
// 如果文件只包含PHP代码,建议省略闭合标记 ?>
// 避免意外的空白字符输出
二、基础语法
2.1 变量与数据类型
PHP
<?php
// ========== 变量声明 ==========
// 所有变量以 $ 开头,区分大小写
$name = "PHP";
$age = 28;
$pi = 3.14159;
$isActive = true;
// 变量变量(动态变量名)
$varName = "name";
echo $$varName; // 输出: PHP(等价于 $name)
// 引用赋值
$a = 10;
$b = &$a; // $b 是 $a 的引用
$b = 20;
echo $a; // 输出: 20($a 也变了)
// ========== 标量数据类型 ==========
// 字符串 (string)
$string1 = '单引号字符串'; // 不解析变量和转义字符
$string2 = "双引号字符串: $name"; // 解析变量
$string3 = <<<EOT
Heredoc语法:可以包含
多行文本,并且解析变量: $name
EOT;
$string4 = <<<'EOT'
Nowdoc语法:类似单引号
不解析变量: $name
EOT;
// 整数 (integer)
$int1 = 42; // 十进制
$int2 = 0b101010; // 二进制(PHP 5.4+)
$int3 = 052; // 八进制
$int4 = 0x2A; // 十六进制
$int5 = 1_000_000; // 数字下划线分隔(PHP 7.4+)
echo PHP_INT_MAX; // 最大整数: 9223372036854775807 (64位)
echo PHP_INT_MIN; // 最小整数
// 浮点数 (float/double)
$float1 = 3.14;
$float2 = 1.2e3; // 科学计数法: 1200
$float3 = 7E-10; // 7 * 10^-10
$float4 = 1_234.567; // 数字下划线分隔(PHP 7.4+)
echo PHP_FLOAT_MAX; // 最大浮点数
echo PHP_FLOAT_MIN; // 最小正浮点数
// 布尔值 (boolean)
$bool1 = true;
$bool2 = false;
// 以下值被视为 false: false, 0, 0.0, "", "0", [], null
// 其他所有值都被视为 true
// 空值 (null)
$nullVar = null; // 表示变量没有值
// 未赋值的变量、unset()的变量、返回null的函数
// ========== 复合数据类型 ==========
// 数组 (array)
$array1 = [1, 2, 3, 4, 5]; // 索引数组
$array2 = array("a", "b", "c"); // 使用array()函数
$array3 = ["name" => "John", "age" => 30]; // 关联数组
// 对象 (object)
$obj = new stdClass();
$obj->property = "value";
// 可调用 (callable) - 表示可调用的函数或方法
$func = function($x) { return $x * 2; };
$callable = "strlen"; // 函数名字符串
$callable2 = [$obj, "methodName"]; // 对象方法数组
// 资源 (resource) - 外部资源引用
$file = fopen("test.txt", "r"); // 文件资源
// $db = mysqli_connect(...); // 数据库连接资源
// ========== 类型检测与转换 ==========
// 类型检测函数
var_dump(is_int(42)); // bool(true)
var_dump(is_float(3.14)); // bool(true)
var_dump(is_string("hello")); // bool(true)
var_dump(is_bool(true)); // bool(true)
var_dump(is_array([1, 2])); // bool(true)
var_dump(is_object($obj)); // bool(true)
var_dump(is_null(null)); // bool(true)
var_dump(is_numeric("123")); // bool(true) - 数字或数字字符串
var_dump(is_scalar(42)); // bool(true) - 标量类型
// gettype() 获取类型
echo gettype(42); // "integer"
echo gettype("hello"); // "string"
// 类型转换(显式)
$num = (int)"123"; // 强制转换为整数: 123
$float = (float)"3.14"; // 强制转换为浮点数: 3.14
$str = (string)42; // 强制转换为字符串: "42"
$bool = (bool)1; // 强制转换为布尔: true
$arr = (array)$obj; // 强制转换为数组
$intval = intval("456"); // intval()函数: 456
$floatval = floatval("3.14"); // floatval()函数: 3.14
$strval = strval(789); // strval()函数: "789"
// 类型转换规则
echo (int)"123abc"; // 123 - 截取数字部分
echo (int)"abc123"; // 0 - 非数字开头
echo (int)true; // 1
echo (int)false; // 0
echo (string)true; // "1"
echo (string)false; // ""
// ========== 类型声明(PHP 7.0+)==========
function add(int $a, int $b): int {
return $a + $b;
}
echo add(5, 3); // 8
// 联合类型(PHP 8.0+)
function formatValue(int|float $value): string {
return number_format($value, 2);
}
// 可空类型(PHP 7.1+)
function findUser(?int $id): ?array {
if ($id === null) {
return null;
}
return ["id" => $id, "name" => "User"];
}
// mixed类型(PHP 8.0+):接受任何类型
function process(mixed $data): mixed {
return $data;
}
// 严格类型模式
declare(strict_types=1);
// 严格模式下,类型必须完全匹配,不会自动转换
// echo add(5, "3"); // 报错,因为"3"是字符串不是int
?>
2.2 常量与魔术常量
PHP
<?php
// ========== 常量定义 ==========
// 使用 define() 函数(全局作用域)
define("APP_NAME", "My PHP App");
define("MAX_RETRY", 3);
define("IS_DEBUG", true);
define("APP_CONFIG", ["host" => "localhost", "port" => 3306]); // PHP 7.0+
// 使用 const 关键字(编译时定义,可在类中)
const PI = 3.141592653589793;
const GREETING = "Hello, World!";
// 区别:define() 运行时定义,const 编译时定义
// const 不能用于条件语句中,define() 可以
if (!defined("ENV")) {
define("ENV", "production");
}
// 检查常量是否存在
var_dump(defined("APP_NAME")); // bool(true)
// ========== 魔术常量(随上下文变化)==========
echo __LINE__; // 当前行号
echo __FILE__; // 文件的完整路径和文件名
echo __DIR__; // 文件所在目录(PHP 5.3+)
echo __FUNCTION__; // 函数名称
echo __CLASS__; // 类名称(含命名空间)
echo __TRAIT__; // Trait名称(含命名空间)
echo __METHOD__; // 类方法名称(含命名空间)
echo __NAMESPACE__; // 当前命名空间名称
// ========== 预定义常量 ==========
echo PHP_VERSION; // PHP版本号: "8.2.0"
echo PHP_MAJOR_VERSION; // 主版本号: 8
echo PHP_MINOR_VERSION; // 次版本号: 2
echo PHP_RELEASE_VERSION; // 修订版本号: 0
echo PHP_OS; // 操作系统: "Linux"
echo PHP_EOL; // 换行符
echo PHP_INT_MAX; // 最大整数
echo DIRECTORY_SEPARATOR; // 目录分隔符: "/" (Linux) 或 "\" (Windows)
echo PATH_SEPARATOR; // 路径分隔符: ":" (Linux) 或 ";" (Windows)
echo DEFAULT_INCLUDE_PATH; // 默认包含路径
?>
2.3 运算符与表达式
PHP
<?php
// ========== 算术运算符 ==========
$a = 10;
$b = 3;
echo $a + $b; // 加法: 13
echo $a - $b; // 减法: 7
echo $a * $b; // 乘法: 30
echo $a / $b; // 除法: 3.3333333333333
echo $a % $b; // 取模: 1
echo $a ** $b; // 幂运算: 1000(PHP 5.6+)
echo -$a; // 取负: -10
// ========== 赋值运算符 ==========
$x = 10;
$x += 5; // $x = $x + 5 -> 15
$x -= 3; // $x = $x - 3 -> 12
$x *= 2; // $x = $x * 2 -> 24
$x /= 4; // $x = $x / 4 -> 6
$x %= 4; // $x = $x % 4 -> 2
$x **= 3; // $x = $x ** 3 -> 8
$x .= "abc"; // $x = $x . "abc" -> "8abc"
// ========== 比较运算符 ==========
var_dump($a == $b); // 等于(值相等): false
var_dump($a === $b); // 全等(值和类型都相等): false
var_dump($a != $b); // 不等于: true
var_dump($a !== $b); // 不全等: true
var_dump($a < $b); // 小于: false
var_dump($a > $b); // 大于: true
var_dump($a <= $b); // 小于等于: false
var_dump($a >= $b); // 大于等于: true
var_dump(10 <=> 5); // 太空船运算符: 1(PHP 7.0+)
var_dump(10 <=> 10); // 0
var_dump(5 <=> 10); // -1
// 注意:== 会进行类型转换
var_dump(0 == "0"); // true
var_dump(0 == ""); // true
var_dump(0 === ""); // false(类型不同)
// ========== 逻辑运算符 ==========
var_dump(true && true); // 逻辑与: true
var_dump(true and false); // 逻辑与(低优先级): false
var_dump(true || false); // 逻辑或: true
var_dump(false or true); // 逻辑或(低优先级): true
var_dump(!true); // 逻辑非: false
var_dump(true xor false); // 逻辑异或: true
// 短路求值
$result = false && someFunction(); // someFunction()不会被调用
$result = true || someFunction(); // someFunction()不会被调用
// ========== 字符串运算符 ==========
$str1 = "Hello";
$str2 = "World";
echo $str1 . " " . $str2; // 连接运算符: "Hello World"
echo $str1 . " " . $str2 . "!"; // 可以链式连接
$str1 .= " PHP"; // 连接赋值: "Hello PHP"
// ========== 递增/递减运算符 ==========
$i = 5;
echo ++$i; // 前递增: 6(先加后用)
echo $i++; // 后递增: 6(先用后加,$i变为7)
echo --$i; // 前递减: 6
echo $i--; // 后递减: 6($i变为5)
// 字符递增
$char = 'A';
echo ++$char; // 'B'
echo ++$char; // 'C'
// 注意:只对字母有效,'Z'递增后变为'AA'
// ========== 位运算符 ==========
$a = 0b1100; // 12
$b = 0b1010; // 10
echo $a & $b; // 按位与: 0b1000 = 8
echo $a | $b; // 按位或: 0b1110 = 14
echo $a ^ $b; // 按位异或: 0b0110 = 6
echo ~$a; // 按位取反: -13
echo $a << 2; // 左移: 0b110000 = 48
echo $a >> 2; // 右移: 0b11 = 3
// ========== 错误控制运算符 ==========
// @ 运算符抑制错误消息
$result = @file_get_contents("nonexistent.txt");
// 不推荐滥用,会影响性能并隐藏真正的问题
// ========== 执行运算符 ==========
// 反引号 `` 执行shell命令
$output = `ls -la`;
echo $output;
// ========== 运算符优先级(从高到低)==========
// 1. clone, new
// 2. **
// 3. ++, --, ~, (int), (float), (string), (array), (object), @
// 4. instanceof
// 5. !
// 6. *, /, %
// 7. +, -, .
// 8. <<, >>
// 9. <, <=, >, >=
// 10. ==, !=, ===, !==, <=>
// 11. &
// 12. ^
// 13. |
// 14. &&
// 15. ||
// 16. ??
// 17. ? :
// 18. =, +=, -=, *=, /=, %=, **=, .=, &=, |=, ^=, <<=, >>=
// 19. and
// 20. xor
// 21. or
?>
2.4 控制结构
PHP
<?php
// ========== if/elseif/else 条件语句 ==========
$score = 85;
if ($score >= 90) {
$grade = "A";
} elseif ($score >= 80) {
$grade = "B";
} elseif ($score >= 70) {
$grade = "C";
} elseif ($score >= 60) {
$grade = "D";
} else {
$grade = "F";
}
echo "成绩: $grade\n"; // 成绩: B
// 替代语法(适用于模板)
if ($score >= 60):
echo "及格\n";
else:
echo "不及格\n";
endif;
// 三元运算符
$status = ($age >= 18) ? "成年" : "未成年";
// 嵌套三元(不推荐,可读性差)
$result = ($score > 90) ? "优秀" : (($score > 60) ? "及格" : "不及格");
// 空合并运算符(PHP 7.0+)
$username = $_GET["user"] ?? "Guest"; // 如果$_GET["user"]不存在或为null,使用默认值
$name = $a ?? $b ?? $c ?? "default"; // 链式空合并
// 空合并赋值运算符(PHP 7.4+)
$config ??= ["host" => "localhost"]; // 如果$config为null则赋值
// ========== switch 语句 ==========
$day = 3;
switch ($day) {
case 1:
echo "Monday\n";
break;
case 2:
echo "Tuesday\n";
break;
case 3:
echo "Wednesday\n"; // 输出: Wednesday
break;
case 4:
echo "Thursday\n";
break;
case 5:
echo "Friday\n";
break;
case 6:
case 7:
echo "Weekend\n";
break;
default:
echo "Invalid day\n";
}
// match表达式(PHP 8.0+)- 严格比较,返回结果
$dayName = match ($day) {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6, 7 => "Weekend",
default => "Invalid day",
};
echo $dayName . "\n"; // Wednesday
// match 支持多个条件映射到同一个值
$result = match (true) {
$score >= 90 => "A",
$score >= 80 => "B",
$score >= 70 => "C",
$score >= 60 => "D",
default => "F",
};
// ========== for 循环 ==========
for ($i = 0; $i < 5; $i++) {
echo "$i "; // 0 1 2 3 4
}
echo "\n";
// 多个初始化/递增表达式
for ($i = 0, $j = 10; $i < 5; $i++, $j--) {
echo "i=$i, j=$j\n";
}
// 无限循环(需要内部break)
for (;;) {
// 处理逻辑
if ($condition) {
break;
}
}
// ========== foreach 循环 ==========
$fruits = ["apple" => "苹果", "banana" => "香蕉", "cherry" => "樱桃"];
// 遍历值
foreach ($fruits as $enName) {
echo "$enName "; // 苹果 香蕉 樱桃
}
echo "\n";
// 遍历键和值
foreach ($fruits as $key => $value) {
echo "$key => $value\n";
}
// 遍历索引数组
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $index => $num) {
echo "numbers[$index] = $num\n";
}
// 通过引用修改数组元素
foreach ($numbers as &$num) {
$num *= 2; // 每个元素翻倍
}
unset($num); // 重要:解除引用,避免后续操作影响
print_r($numbers); // [2, 4, 6, 8, 10]
// ========== while 循环 ==========
$count = 0;
while ($count < 5) {
echo "$count "; // 0 1 2 3 4
$count++;
}
echo "\n";
// ========== do-while 循环(至少执行一次)==========
$count = 0;
do {
echo "$count "; // 0
$count++;
} while ($count < 0); // 条件为假,但至少执行了一次
echo "\n";
// ========== 循环控制 ==========
// break:退出循环
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // 退出循环
}
echo "$i ";
}
echo "\n"; // 输出: 0 1 2 3 4
// break N:退出多层循环
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($i == 1 && $j == 1) {
break 2; // 退出两层循环
}
echo "($i, $j) ";
}
}
echo "\n";
// continue:跳过当前迭代
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // 跳过偶数
}
echo "$i "; // 1 3 5 7 9
}
echo "\n";
// continue N:跳到外层循环
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($j == 1) {
continue 2; // 跳到外层循环的下一次迭代
}
echo "($i, $j) ";
}
}
echo "\n";
// ========== goto 语句(不推荐,但可用)==========
$i = 0;
start:
echo "$i ";
$i++;
if ($i < 5) {
goto start;
}
echo "\n"; // 0 1 2 3 4
?>
2.5 函数定义与调用
PHP
<?php
// ========== 基本函数定义 ==========
function greet($name) {
return "Hello, $name!";
}
echo greet("World") . "\n"; // Hello, World!
// ========== 参数类型 ==========
// 必需参数
function requiredParams($a, $b) {
return $a + $b;
}
// 默认参数
function greetWithTitle($name, $title = "Mr.") {
return "Hello, $title $name!";
}
echo greetWithTitle("Smith") . "\n"; // Hello, Mr. Smith!
echo greetWithTitle("Jane", "Ms.") . "\n"; // Hello, Ms. Jane!
// 默认参数必须放在必需参数之后
function createUser($name, $role = "user", $active = true) {
return compact("name", "role", "active");
}
// 可变参数(PHP 5.6+)
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4, 5) . "\n"; // 15
// 参数解包(PHP 5.6+)
$nums = [1, 2, 3];
echo sum(...$nums) . "\n"; // 6
// 命名参数(PHP 8.0+)
function createProduct($name, $price, $category = "general", $stock = 0) {
return compact("name", "price", "category", "stock");
}
// 可以跳过默认参数,直接指定后面的参数
$product = createProduct(name: "Laptop", price: 999.99, stock: 50);
print_r($product);
// ========== 类型声明 ==========
// 参数类型声明(PHP 7.0+)
function add(int $a, int $b): int {
return $a + $b;
}
// 联合类型(PHP 8.0+)
function formatNumber(int|float $number): string {
return number_format($number, 2);
}
// 可空类型(PHP 7.1+)
function findById(?int $id): ?array {
if ($id === null) {
return null;
}
return ["id" => $id];
}
// void 返回类型(PHP 7.1+)
function logMessage(string $message): void {
echo "[LOG] $message\n";
// 不需要return语句
}
// never 返回类型(PHP 8.1+)
function redirect(string $url): never {
header("Location: $url");
exit();
}
// 返回static类型(PHP 8.0+)
class Builder {
public function setName(string $name): static {
$this->name = $name;
return $this;
}
}
// ========== 参数传递方式 ==========
// 按值传递(默认)
function increment($value) {
$value++;
return $value;
}
$num = 5;
echo increment($num) . "\n"; // 6
echo $num . "\n"; // 5(原值不变)
// 按引用传递
function incrementRef(&$value) {
$value++;
return $value;
}
$num2 = 5;
echo incrementRef($num2) . "\n"; // 6
echo $num2 . "\n"; // 6(原值被修改)
// ========== 返回值 ==========
// 返回多个值(使用数组)
function getUserInfo(): array {
return ["name" => "John", "age" => 30, "email" => "john@example.com"];
}
["name" => $name, "age" => $age] = getUserInfo(); // 数组解构(PHP 7.1+)
echo "$name, $age\n";
// 返回引用
function &getReference() {
static $value = 0;
return $value;
}
$ref = &getReference();
$ref = 10;
echo getReference() . "\n"; // 10
// ========== 变量函数 ==========
function sayHello() {
return "Hello!";
}
$funcName = "sayHello";
echo $funcName() . "\n"; // Hello!
// ========== 匿名函数(闭包)==========
// 基本匿名函数
$greet = function($name) {
return "Hello, $name!";
};
echo $greet("World") . "\n"; // Hello, World!
// 使用外部变量(use 关键字)
$prefix = "Mr.";
$greetWithPrefix = function($name) use ($prefix) {
return "Hello, $prefix $name!";
};
echo $greetWithPrefix("Smith") . "\n"; // Hello, Mr. Smith!
// 引用外部变量(可修改)
$count = 0;
$increment = function() use (&$count) {
$count++;
};
$increment();
$increment();
echo $count . "\n"; // 2
// 箭头函数(PHP 7.4+)
$numbers = [1, 2, 3, 4, 5];
$factor = 2;
$doubled = array_map(fn($n) => $n * $factor, $numbers);
print_r($doubled); // [2, 4, 6, 8, 10]
// 箭头函数自动捕获外部变量(按值),不能修改
// ========== 递归函数 ==========
function factorial(int $n): int {
if ($n <= 1) {
return 1;
}
return $n * factorial($n - 1);
}
echo factorial(5) . "\n"; // 120
// 尾递归斐波那契
function fibonacci(int $n, int $a = 0, int $b = 1): int {
if ($n == 0) return $a;
if ($n == 1) return $b;
return fibonacci($n - 1, $b, $a + $b);
}
echo fibonacci(10) . "\n"; // 55
// ========== 生成器(Generator)==========
// 使用yield返回迭代器,节省内存
function rangeGenerator(int $start, int $end, int $step = 1): Generator {
for ($i = $start; $i <= $end; $i += $step) {
yield $i;
}
}
foreach (rangeGenerator(1, 5) as $num) {
echo "$num "; // 1 2 3 4 5
}
echo "\n";
// 带键的生成器
function keyValueGenerator(): Generator {
yield "name" => "John";
yield "age" => 30;
yield "city" => "New York";
}
foreach (keyValueGenerator() as $key => $value) {
echo "$key: $value\n";
}
// yield from:委托生成器(PHP 7.0+)
function combinedGenerator(): Generator {
yield from rangeGenerator(1, 3);
yield from rangeGenerator(10, 12);
}
foreach (combinedGenerator() as $num) {
echo "$num "; // 1 2 3 10 11 12
}
echo "\n";
?>
三、数组与字符串
3.1 数组详解
PHP
<?php
// ========== 数组创建 ==========
// 索引数组
$colors = ["red", "green", "blue"];
$colors2 = array("red", "green", "blue");
// 关联数组
$person = [
"name" => "John",
"age" => 30,
"city" => "New York",
];
// 混合数组
$mixed = [
"apple", // 索引0
"name" => "John", // 关联键
"banana", // 索引1(自动分配)
5 => "cherry", // 指定索引
"date", // 索引6(自动递增)
];
// 多维数组
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
echo $matrix[1][2] . "\n"; // 6
// 使用 range() 创建数组
$numbers = range(1, 10); // [1, 2, 3, ..., 10]
$letters = range('a', 'z'); // ['a', 'b', 'c', ..., 'z']
$even = range(0, 20, 2); // [0, 2, 4, ..., 20]
// 使用 array_fill() 填充数组
$filled = array_fill(0, 5, "hello"); // ["hello", "hello", "hello", "hello", "hello"]
// ========== 数组访问 ==========
echo $colors[0] . "\n"; // red
echo $person["name"] . "\n"; // John
// 检查键是否存在
var_dump(array_key_exists("name", $person)); // bool(true)
var_dump(isset($person["name"])); // bool(true)
// 区别:array_key_exists对null值返回true,isset返回false
$arr = ["key" => null];
var_dump(array_key_exists("key", $arr)); // true
var_dump(isset($arr["key"])); // false
// 检查值是否存在
var_dump(in_array("red", $colors)); // bool(true)
var_dump(in_array("yellow", $colors)); // bool(false)
// 获取键/值
var_dump(array_keys($person)); // ["name", "age", "city"]
var_dump(array_values($person)); // ["John", 30, "New York"]
// ========== 数组添加/删除 ==========
// 末尾添加
$colors[] = "yellow"; // 自动分配索引
array_push($colors, "purple", "orange"); // 一次添加多个
// 开头添加
array_unshift($colors, "white"); // 在开头添加
// 末尾删除
$last = array_pop($colors); // 删除并返回最后一个元素
// 开头删除
$first = array_shift($colors); // 删除并返回第一个元素
// 删除指定元素
unset($colors[1]); // 删除索引1的元素
// 注意:索引不会被重新排序,会产生间隙
// 按值删除
$colors = array_diff($colors, ["red"]); // 删除值为"red"的所有元素
// 提取子数组
$subset = array_slice($colors, 1, 2); // 从索引1开始,取2个元素
// 替换子数组
array_splice($colors, 1, 2, ["new1", "new2"]); // 从索引1开始,删除2个,插入新元素
// ========== 数组排序 ==========
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// 升序排序(修改原数组,不保留键)
sort($numbers);
print_r($numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
// 降序排序
rsort($numbers);
print_r($numbers); // [9, 6, 5, 4, 3, 2, 1, 1]
// 升序排序(保留键)
asort($person);
// 降序排序(保留键)
arsort($person);
// 按键升序排序
ksort($person);
// 按键降序排序
krsort($person);
// 自定义排序
usort($people, function($a, $b) {
return $a["age"] <=> $b["age"]; // 按年龄排序
});
// 自然排序("img1", "img2", "img10" 而不是 "img1", "img10", "img2")
natsort($filenames);
// ========== 数组遍历 ==========
// foreach 遍历
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
// for 遍历(仅索引数组)
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . " ";
}
echo "\n";
// 使用数组指针
$fruits = ["apple", "banana", "cherry"];
echo current($fruits) . "\n"; // apple - 当前元素
echo next($fruits) . "\n"; // banana - 下一个
echo prev($fruits) . "\n"; // apple - 上一个
echo end($fruits) . "\n"; // cherry - 最后一个
reset($fruits); // 重置指针到开头
// ========== 数组转换 ==========
// 数组转字符串
$str = implode(", ", $colors); // "red, green, blue"
$str = join(", ", $colors); // 同 implode
// 字符串转数组
$arr = explode(", ", "red, green, blue"); // ["red", "green", "blue"]
$arr = str_split("hello"); // ["h", "e", "l", "l", "o"]
// 数组合并
$merged = array_merge($arr1, $arr2); // 索引数组:重新索引,关联数组:同名键后者覆盖
$merged = [...$arr1, ...$arr2]; // PHP 7.4+ 数组展开
// 求交集
$intersect = array_intersect($arr1, $arr2); // 值交集
$intersectKey = array_intersect_key($arr1, $arr2); // 键交集
// 求差集
$diff = array_diff($arr1, $arr2); // 值差集
// 去重
$unique = array_unique($numbers);
// 反转
$reversed = array_reverse($numbers);
// 随机打乱
shuffle($numbers); // 修改原数组
// 随机取一个或多个
$randomKey = array_rand($person); // 随机键
$randomKeys = array_rand($person, 2); // 随机2个键
// ========== 数组函数 ==========
// 数组长度
echo count($numbers) . "\n"; // 8
echo sizeof($numbers) . "\n"; // 同 count
// 求和
echo array_sum($numbers) . "\n"; // 所有元素之和
// 乘积
echo array_product([2, 3, 4]) . "\n"; // 24
// 最大值/最小值
echo max($numbers) . "\n";
echo min($numbers) . "\n";
// 过滤
$even = array_filter($numbers, fn($n) => $n % 2 == 0);
// 映射
$squared = array_map(fn($n) => $n * $n, $numbers);
// 归约
$total = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// 搜索
$key = array_search(5, $numbers); // 返回键名
// 列提取(从二维数组中提取一列)
$users = [
["id" => 1, "name" => "Alice", "age" => 25],
["id" => 2, "name" => "Bob", "age" => 30],
["id" => 3, "name" => "Charlie", "age" => 35],
];
$names = array_column($users, "name"); // ["Alice", "Bob", "Charlie"]
$usersById = array_column($users, null, "id"); // 以id为键重新索引
// 数组分块
$chunks = array_chunk($numbers, 3); // 每3个一组
// 数组填充到指定长度
$padded = array_pad($numbers, 10, 0); // 不足10个,用0填充
// 数组替换
$replaced = array_replace($arr1, $arr2); // 用$arr2的值替换$arr1中同名键的值
// 数组解构(PHP 7.1+)
["name" => $name, "age" => $age] = $person;
echo "$name, $age\n"; // John, 30
// 列表解构
[$first, $second, $third] = $colors;
echo "$first, $second, $third\n"; // red, green, blue
// 跳过元素
[, , $third] = $colors;
echo $third . "\n"; // blue
?>
3.2 字符串操作
PHP
<?php
// ========== 基本字符串函数 ==========
$str = "Hello, PHP World!";
// 字符串长度
echo strlen($str) . "\n"; // 18(字节数)
echo mb_strlen($str) . "\n"; // 18(字符数,多字节安全)
// 字符串位置
echo strpos($str, "PHP") . "\n"; // 7(第一次出现位置)
echo strrpos($str, "o") . "\n"; // 13(最后一次出现位置)
echo stripos($str, "php") . "\n"; // 7(忽略大小写)
echo str_contains($str, "PHP") . "\n"; // true(PHP 8.0+)
echo str_starts_with($str, "Hello") . "\n"; // true(PHP 8.0+)
echo str_ends_with($str, "!") . "\n"; // true(PHP 8.0+)
// 字符串截取
echo substr($str, 0, 5) . "\n"; // "Hello"
echo substr($str, 7, 3) . "\n"; // "PHP"
echo substr($str, -6) . "\n"; // "World!"(从末尾开始)
echo substr($str, 0, -1) . "\n"; // "Hello, PHP World"
echo mb_substr("你好世界", 0, 2) . "\n"; // "你好"(多字节安全)
// 字符串替换
echo str_replace("PHP", "JavaScript", $str) . "\n"; // "Hello, JavaScript World!"
echo str_ireplace("php", "JS", $str) . "\n"; // 忽略大小写
echo substr_replace($str, "Universe", 13, 5) . "\n"; // 替换指定位置
// 大小写转换
echo strtoupper($str) . "\n"; // "HELLO, PHP WORLD!"
echo strtolower($str) . "\n"; // "hello, php world!"
echo ucfirst($str) . "\n"; // 首字母大写
echo ucwords($str) . "\n"; // 每个单词首字母大写
echo lcfirst($str) . "\n"; // 首字母小写
// 去除空白
$text = " Hello World \n";
echo trim($text) . "\n"; // "Hello World"(去除两端空白)
echo ltrim($text) . "\n"; // 去除左侧空白
echo rtrim($text) . "\n"; // 去除右侧空白
echo trim($text, " Hd") . "\n"; // 去除指定字符: "ello Worl"
// 字符串分割
$parts = explode(", ", $str); // ["Hello", "PHP World!"]
$parts = str_split("hello", 2); // ["he", "ll", "o"]
$parts = preg_split("/[\s,]+/", $str); // 正则分割
// 字符串格式化
$name = "John";
$age = 30;
echo sprintf("Name: %s, Age: %d", $name, $age) . "\n"; // "Name: John, Age: 30"
printf("Price: %.2f\n", 99.99); // "Price: 99.99"(直接输出)
// 占位符说明
// %s - 字符串
// %d - 整数
// %f - 浮点数
// %.2f - 浮点数保留2位小数
// %x - 十六进制
// %o - 八进制
// %% - 百分号
// 字符串重复
echo str_repeat("Hello ", 3) . "\n"; // "Hello Hello Hello "
// 字符串填充
echo str_pad("Hello", 10, "-") . "\n"; // "Hello-----"
echo str_pad("Hello", 10, "-", STR_PAD_LEFT) . "\n"; // "-----Hello"
echo str_pad("Hello", 10, "-", STR_PAD_BOTH) . "\n"; // "--Hello---"
// 字符串反转
echo strrev("Hello") . "\n"; // "olleH"
// 字符串打乱
echo str_shuffle("Hello") . "\n"; // 随机排列
// 字符串比较
echo strcmp("abc", "abc") . "\n"; // 0(相等)
echo strcmp("abc", "abd") . "\n"; // -1(小于)
echo strcasecmp("ABC", "abc") . "\n"; // 0(忽略大小写)
echo strnatcmp("img1", "img10") . "\n"; // -1(自然排序比较)
// 字符串统计
echo substr_count($str, "o") . "\n"; // 2(子串出现次数)
echo str_word_count($str) . "\n"; // 3(单词数量)
// 字符串编码
echo htmlspecialchars("<script>alert('xss')</script>") . "\n";
// <script>alert('xss')</script>
echo htmlentities("© 2024") . "\n"; // © 2024
echo html_entity_decode("© 2024") . "\n"; // © 2024
// URL编码
echo urlencode("Hello World!") . "\n"; // "Hello+World%21"
echo urldecode("Hello+World%21") . "\n"; // "Hello World!"
// 字符串转义
echo addslashes("It's a \"test\"") . "\n"; // "It\'s a \"test\""
echo addcslashes("hello", "el") . "\n"; // "h\e\l\lo"
// 字符串加密
echo md5("password") . "\n"; // 32位MD5哈希(不安全,不用于密码)
echo sha1("password") . "\n"; // 40位SHA-1哈希(不安全)
echo hash("sha256", "password") . "\n"; // SHA-256哈希
// ========== 正则表达式 ==========
// 匹配
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
$email = "user@example.com";
var_dump(preg_match($pattern, $email)); // int(1) - 匹配成功
// 匹配所有
preg_match_all("/\d+/", "age: 25, height: 180", $matches);
print_r($matches[0]); // ["25", "180"]
// 替换
$result = preg_replace("/\d+/", "***", "phone: 1234567890");
echo $result . "\n"; // "phone: ***"
// 回调替换
$result = preg_replace_callback("/\d+/", fn($m) => $m[0] * 2, "price: 100");
echo $result . "\n"; // "price: 200"
// 分割
$parts = preg_split("/[\s,]+/", "apple, banana cherry");
print_r($parts); // ["apple", "banana", "cherry"]
// 过滤(返回匹配的部分)
$result = preg_grep("/^a/", ["apple", "banana", "avocado", "cherry"]);
print_r($result); // ["apple", "avocado"]
// 转义正则特殊字符
$escaped = preg_quote("http://example.com?q=test");
echo $escaped . "\n"; // "http\://example\.com\?q\=test"
?>
四、面向对象编程
4.1 类与对象
PHP
<?php
// ========== 类定义 ==========
class Person
{
// 属性(成员变量)
public string $name; // PHP 7.4+ 类型属性
protected int $age;
private string $email;
public static int $count = 0; // 静态属性
private const SPECIES = "Homo Sapiens"; // 私有常量(PHP 7.1+)
// 构造方法
public function __construct(
string $name,
int $age,
string $email
) {
$this->name = $name;
$this->age = $age;
$this->email = $email;
self::$count++;
}
// 析构方法
public function __destruct()
{
self::$count--;
}
// 实例方法
public function introduce(): string
{
return "Hello, my name is {$this->name}, I'm {$this->age} years old.";
}
// Getter方法
public function getAge(): int
{
return $this->age;
}
// Setter方法(带验证)
public function setAge(int $age): void
{
if ($age < 0 || $age > 150) {
throw new InvalidArgumentException("Invalid age: $age");
}
$this->age = $age;
}
// 静态方法
public static function getCount(): int
{
return self::$count;
}
// 私有方法
private function validateEmail(string $email): bool
{
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
}
// ========== 构造器属性提升(PHP 8.0+)==========
class User
{
public function __construct(
public string $name,
public int $age,
private string $email,
protected string $role = "user",
public readonly string $id = "", // readonly属性(PHP 8.1+)
) {
if ($this->id === "") {
$this->id = uniqid("user_");
}
}
}
// ========== 创建和使用对象 ==========
$person = new Person("Alice", 25, "alice@example.com");
echo $person->name . "\n"; // Alice
echo $person->introduce() . "\n"; // Hello, my name is Alice...
echo Person::getCount() . "\n"; // 1
// 检查对象
var_dump($person instanceof Person); // bool(true)
// 克隆对象
$clone = clone $person;
// __clone() 方法会在克隆时调用
// ========== readonly 类(PHP 8.2+)==========
readonly class Config
{
public function __construct(
public string $host,
public int $port,
public string $dbName,
) {}
}
$config = new Config("localhost", 3306, "myapp");
// $config->host = "other"; // 错误:readonly属性不能修改
?>
4.2 继承
PHP
<?php
// ========== 基本继承 ==========
class Animal
{
public function __construct(
protected string $name,
protected int $age,
) {}
public function speak(): string
{
return "Some generic animal sound";
}
public function getName(): string
{
return $this->name;
}
final public function getAge(): int // final方法不能被重写
{
return $this->age;
}
}
class Dog extends Animal
{
private string $breed;
public function __construct(string $name, int $age, string $breed)
{
parent::__construct($name, $age); // 调用父类构造
$this->breed = $breed;
}
// 重写父类方法
public function speak(): string
{
return "Woof! My name is {$this->name}";
}
public function getBreed(): string
{
return $this->breed;
}
}
class Cat extends Animal
{
public function speak(): string
{
return "Meow!";
}
}
$dog = new Dog("Buddy", 3, "Golden Retriever");
echo $dog->speak() . "\n"; // Woof! My name is Buddy
echo $dog->getAge() . "\n"; // 3
$cat = new Cat("Whiskers", 2);
echo $cat->speak() . "\n"; // Meow!
// ========== final 类(不能被继承)==========
final class StringUtils
{
public static function truncate(string $str, int $maxLen): string
{
return mb_strlen($str) > $maxLen
? mb_substr($str, 0, $maxLen) . "..."
: $str;
}
}
// ========== 后期静态绑定 ==========
class Base
{
public static function create(): static
{
return new static(); // static 指向调用时的类
}
public static function who(): string
{
return __CLASS__;
}
public static function test(): string
{
return static::who(); // 后期静态绑定
}
}
class Child extends Base
{
public static function who(): string
{
return __CLASS__;
}
}
echo Base::test() . "\n"; // Base
echo Child::test() . "\n"; // Child(static::who() 调用 Child::who())
// ========== 对象继承检查 ==========
var_dump($dog instanceof Animal); // true
var_dump($dog instanceof Dog); // true
var_dump($cat instanceof Dog); // false
// 获取父类名
echo get_parent_class($dog) . "\n"; // Animal
echo get_parent_class('Dog') . "\n"; // Animal
// 检查是否为子类
var_dump(is_subclass_of($dog, 'Animal')); // true
var_dump(is_subclass_of('Dog', 'Animal')); // true
?>
4.3 接口与抽象类
PHP
<?php
// ========== 接口定义 ==========
interface Logger
{
public function log(string $message, string $level): void;
public function getLogs(): array;
}
interface Formatter
{
public function format(array $data): string;
}
// 接口可以继承多个接口
interface AdvancedLogger extends Logger, Formatter
{
public function logWithContext(string $message, array $context): void;
}
// ========== 实现接口 ==========
class FileLogger implements Logger
{
private string $filePath;
private array $logs = [];
public function __construct(string $filePath)
{
$this->filePath = $filePath;
}
public function log(string $message, string $level = "INFO"): void
{
$entry = "[{$level}] " . date("Y-m-d H:i:s") . " - {$message}";
$this->logs[] = $entry;
file_put_contents($this->filePath, $entry . PHP_EOL, FILE_APPEND);
}
public function getLogs(): array
{
return $this->logs;
}
}
// 实现多个接口
class DatabaseLogger implements Logger, Formatter
{
private PDO $pdo;
private array $logs = [];
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function log(string $message, string $level = "INFO"): void
{
$this->logs[] = compact("message", "level");
$stmt = $this->pdo->prepare(
"INSERT INTO logs (message, level, created_at) VALUES (?, ?, NOW())"
);
$stmt->execute([$message, $level]);
}
public function getLogs(): array
{
return $this->logs;
}
public function format(array $data): string
{
return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
}
// ========== 抽象类 ==========
abstract class Shape
{
protected string $color;
public function __construct(string $color = "black")
{
$this->color = $color;
}
// 抽象方法:子类必须实现
abstract public function getArea(): float;
abstract public function getPerimeter(): float;
// 具体方法:子类可以继承
public function getColor(): string
{
return $this->color;
}
public function describe(): string
{
return sprintf(
"A %s shape with area %.2f and perimeter %.2f",
$this->color,
$this->getArea(),
$this->getPerimeter()
);
}
}
class Circle extends Shape
{
public function __construct(
private float $radius,
string $color = "black"
) {
parent::__construct($color);
}
public function getArea(): float
{
return pi() * $this->radius ** 2;
}
public function getPerimeter(): float
{
return 2 * pi() * $this->radius;
}
}
class Rectangle extends Shape
{
public function __construct(
private float $width,
private float $height,
string $color = "black"
) {
parent::__construct($color);
}
public function getArea(): float
{
return $this->width * $this->height;
}
public function getPerimeter(): float
{
return 2 * ($this->width + $this->height);
}
}
// 多态:统一处理不同形状
function printShapeInfo(Shape $shape): void
{
echo $shape->describe() . "\n";
}
$circle = new Circle(5, "red");
$rectangle = new Rectangle(4, 6, "blue");
printShapeInfo($circle); // A red shape with area 78.54...
printShapeInfo($rectangle); // A blue shape with area 24.00...
?>
4.4 Trait(代码复用)
PHP
<?php
// ========== Trait 定义与使用 ==========
trait Timestampable
{
private \DateTimeImmutable $createdAt;
private ?\DateTimeImmutable $updatedAt = null;
public function initializeTimestamps(): void
{
$this->createdAt = new \DateTimeImmutable();
}
public function updateTimestamp(): void
{
$this->updatedAt = new \DateTimeImmutable();
}
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
}
trait SoftDeletable
{
private ?\DateTimeImmutable $deletedAt = null;
public function delete(): void
{
$this->deletedAt = new \DateTimeImmutable();
}
public function restore(): void
{
$this->deletedAt = null;
}
public function isDeleted(): bool
{
return $this->deletedAt !== null;
}
}
trait Identifiable
{
public function __construct(
private string $id,
) {}
public function getId(): string
{
return $this->id;
}
}
// ========== 使用多个Trait ==========
class Product
{
use Timestampable, SoftDeletable, Identifiable;
public function __construct(
string $id,
private string $name,
private float $price,
) {
$this->initializeTimestamps();
}
public function getName(): string
{
return $this->name;
}
public function getPrice(): float
{
return $this->price;
}
}
$product = new Product("p1", "Laptop", 999.99);
echo $product->getId() . "\n"; // p1
echo $product->getName() . "\n"; // Laptop
echo $product->isDeleted() . "\n"; // false
$product->delete();
echo $product->isDeleted() . "\n"; // true
// ========== Trait 冲突解决 ==========
trait A
{
public function say(): string
{
return "Hello from A";
}
}
trait B
{
public function say(): string
{
return "Hello from B";
}
}
class ConflictResolver
{
use A, B {
A::say insteadof B; // 使用A的say方法
B::say as sayFromB; // 将B的say方法重命名为sayFromB
}
}
$resolver = new ConflictResolver();
echo $resolver->say() . "\n"; // Hello from A
echo $resolver->sayFromB() . "\n"; // Hello from B
// ========== Trait 抽象方法 ==========
trait Validatable
{
abstract public function getRules(): array;
public function validate(): array
{
$errors = [];
foreach ($this->getRules() as $field => $rules) {
// 验证逻辑...
}
return $errors;
}
}
// ========== Trait 可见性修改 ==========
trait MyTrait
{
public function publicMethod(): string
{
return "public";
}
private function privateMethod(): string
{
return "private";
}
}
class VisibilityModifier
{
use MyTrait {
publicMethod as private; // 将public改为private
privateMethod as public; // 将private改为public
}
}
?>
4.5 魔术方法
PHP
<?php
class MagicMethods
{
private array $data = [];
private array $methods = [];
// ========== __construct: 构造方法 ==========
public function __construct(array $data = [])
{
$this->data = $data;
}
// ========== __destruct: 析构方法 ==========
public function __destruct()
{
echo "Object is being destroyed\n";
}
// ========== __get: 访问不可访问属性 ==========
public function __get(string $name): mixed
{
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
throw new \Exception("Property '$name' does not exist");
}
// ========== __set: 设置不可访问属性 ==========
public function __set(string $name, mixed $value): void
{
$this->data[$name] = $value;
}
// ========== __isset: 检查不可访问属性 ==========
public function __isset(string $name): bool
{
return isset($this->data[$name]);
}
// ========== __unset: 删除不可访问属性 ==========
public function __unset(string $name): void
{
unset($this->data[$name]);
}
// ========== __call: 调用不可访问方法 ==========
public function __call(string $name, array $arguments): mixed
{
if (isset($this->methods[$name])) {
return ($this->methods[$name])(...$arguments);
}
throw new \Exception("Method '$name' does not exist");
}
// ========== __callStatic: 调用不可访问静态方法 ==========
public static function __callStatic(string $name, array $arguments): mixed
{
echo "Calling static method '$name'\n";
return null;
}
// ========== __toString: 字符串表示 ==========
public function __toString(): string
{
return json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
// ========== __invoke: 作为函数调用 ==========
public function __invoke(string $key): mixed
{
return $this->data[$key] ?? null;
}
// ========== __clone: 克隆时调用 ==========
public function __clone(): void
{
// 深拷贝数据
$this->data = array_map(
fn($item) => is_object($item) ? clone $item : $item,
$this->data
);
}
// ========== __serialize / __unserialize: 序列化控制 ==========
public function __serialize(): array
{
return ["data" => $this->data];
}
public function __unserialize(array $data): void
{
$this->data = $data["data"];
}
// ========== __debugInfo: 控制 var_dump 输出 ==========
public function __debugInfo(): array
{
return [
"data" => $this->data,
"count" => count($this->data),
];
}
}
// 使用示例
$obj = new MagicMethods(["name" => "John", "age" => 30]);
echo $obj->name . "\n"; // John(通过 __get)
$obj->city = "New York"; // 通过 __set
echo $obj . "\n"; // 通过 __toString 输出JSON
echo $obj("name") . "\n"; // John(通过 __invoke)
?>
4.6 枚举(PHP 8.1+)
PHP
<?php
// ========== 基本枚举 ==========
enum Status: string
{
case DRAFT = "draft";
case PUBLISHED = "published";
case ARCHIVED = "archived";
public function label(): string
{
return match ($this) {
self::DRAFT => "草稿",
self::PUBLISHED => "已发布",
self::ARCHIVED => "已归档",
};
}
public function canTransitionTo(self $target): bool
{
return match ($this) {
self::DRAFT => $target === self::PUBLISHED,
self::PUBLISHED => $target === self::ARCHIVED,
self::ARCHIVED => false,
};
}
}
$status = Status::PUBLISHED;
echo $status->value . "\n"; // published
echo $status->label() . "\n"; // 已发布
// 枚举方法
var_dump(Status::cases()); // 所有枚举值
var_dump(Status::from("draft")); // 从值创建
var_dump(Status::tryFrom("invalid")); // 返回null而不是抛出异常
// ========== 纯枚举(无标量值)==========
enum Direction
{
case North;
case South;
case East;
case West;
public function opposite(): self
{
return match ($this) {
self::North => self::South,
self::South => self::North,
self::East => self::West,
self::West => self::East,
};
}
}
?>
五、标准库详解
5.1 日期与时间
PHP
<?php
// ========== DateTime 类 ==========
// 创建日期时间对象
$now = new DateTime();
$specific = new DateTime("2024-01-15 10:30:00");
$fromFormat = DateTime::createFromFormat("Y-m-d", "2024-06-01");
echo $now->format("Y-m-d H:i:s") . "\n"; // 2024-06-15 14:30:00
echo $now->format("Y年m月d日") . "\n"; // 2024年06月15日
// 常用格式字符
// Y - 4位年份(2024)
// y - 2位年份(24)
// m - 月份(01-12)
// d - 日期(01-31)
// H - 24小时制(00-23)
// i - 分钟(00-59)
// s - 秒(00-59)
// l - 星期几完整名称(Monday)
// D - 星期几缩写(Mon)
// F - 月份完整名称(January)
// M - 月份缩写(Jan)
// U - Unix时间戳
// 日期修改
$now->modify("+1 day");
$now->modify("+2 weeks");
$now->modify("+1 month");
$now->modify("-1 year");
$now->modify("first day of next month");
$now->modify("last day of this month");
echo $now->format("Y-m-d") . "\n";
// 日期比较
$date1 = new DateTime("2024-01-01");
$date2 = new DateTime("2024-12-31");
$interval = $date1->diff($date2);
echo $interval->days . " days\n"; // 365 days
echo $interval->format("%y years, %m months, %d days") . "\n";
// 日期比较运算
if ($date1 < $date2) {
echo "date1 is earlier\n";
}
// ========== DateInterval 类 ==========
$interval = new DateInterval("P1M2D"); // 1个月2天
$now->add($interval);
$now->sub(new DateInterval("P1D")); // 减去1天
// 间隔格式: P[yY][mM][dD][T[hH][iM][sS]]
$interval = new DateInterval("P1Y2M3DT4H5M6S"); // 1年2月3天4小时5分6秒
// ========== DatePeriod 类(日期范围)==========
$start = new DateTime("2024-01-01");
$end = new DateTime("2024-01-10");
$interval = new DateInterval("P1D");
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
echo $date->format("Y-m-d") . "\n";
}
// ========== DateTimeImmutable(不可变)==========
$immutable = new DateTimeImmutable("2024-01-01");
$nextDay = $immutable->modify("+1 day"); // 返回新对象,原对象不变
echo $immutable->format("Y-m-d") . "\n"; // 2024-01-01
echo $nextDay->format("Y-m-d") . "\n"; // 2024-01-02
// ========== 时区处理 ==========
$timezone = new DateTimeZone("Asia/Shanghai");
$date = new DateTime("now", $timezone);
echo $date->format("Y-m-d H:i:s T") . "\n";
// 切换时区
$date->setTimezone(new DateTimeZone("America/New_York"));
echo $date->format("Y-m-d H:i:s T") . "\n";
// 获取所有时区
// $timezones = DateTimeZone::listIdentifiers();
// ========== 传统日期函数 ==========
echo date("Y-m-d H:i:s") . "\n"; // 当前日期时间
echo time() . "\n"; // Unix时间戳
echo strtotime("+1 day") . "\n"; // 字符串转时间戳
echo date("Y-m-d", strtotime("2024-01-01 +1 month")) . "\n";
// 检查日期是否有效
var_dump(checkdate(2, 29, 2024)); // bool(true) - 2024是闰年
var_dump(checkdate(2, 29, 2023)); // bool(false)
// 设置默认时区
date_default_timezone_set("Asia/Shanghai");
echo date_default_timezone_get() . "\n";
?>
5.2 数学函数
PHP
<?php
// ========== 基本数学函数 ==========
echo abs(-10) . "\n"; // 绝对值: 10
echo ceil(3.14) . "\n"; // 向上取整: 4
echo floor(3.14) . "\n"; // 向下取整: 3
echo round(3.14) . "\n"; // 四舍五入: 3
echo round(3.14159, 2) . "\n"; // 保留2位小数: 3.14
echo round(3.5) . "\n"; // 4(PHP默认四舍五入到最近的偶数: 4)
echo round(4.5) . "\n"; // 4(银行家舍入)
echo round(3.5, 0, PHP_ROUND_HALF_UP) . "\n"; // 4(标准四舍五入)
echo round(3.5, 0, PHP_ROUND_HALF_DOWN) . "\n"; // 3(向下舍入)
// 最大/最小值
echo max(1, 5, 3, 9, 2) . "\n"; // 9
echo min(1, 5, 3, 9, 2) . "\n"; // 1
echo max([1, 5, 3, 9, 2]) . "\n"; // 9
// 幂运算
echo pow(2, 10) . "\n"; // 1024
echo sqrt(16) . "\n"; // 4
echo exp(1) . "\n"; // e^1: 2.718281828459
echo log(10) . "\n"; // 自然对数: 2.302585092994
echo log10(100) . "\n"; // 10为底对数: 2
// 三角函数
echo sin(pi() / 2) . "\n"; // 1
echo cos(pi()) . "\n"; // -1
echo tan(pi() / 4) . "\n"; // 1
echo deg2rad(180) . "\n"; // 角度转弧度: 3.1415926535898
echo rad2deg(pi()) . "\n"; // 弧度转角度: 180
// 随机数
echo rand(1, 100) . "\n"; // 随机整数(1-100)
echo mt_rand(1, 100) . "\n"; // 更好的随机数生成器
echo random_int(1, 100) . "\n"; // 密码学安全的随机整数(PHP 7.0+)
echo random_bytes(16) . "\n"; // 密码学安全的随机字节(PHP 7.0+)
// 格式化数字
echo number_format(1234567.89) . "\n"; // 1,234,568
echo number_format(1234567.89, 2) . "\n"; // 1,234,567.89
echo number_format(1234567.89, 2, ",", ".") . "\n"; // 1.234.567,89
// ========== 进制转换 ==========
echo decbin(10) . "\n"; // 十进制转二进制: 1010
echo bindec("1010") . "\n"; // 二进制转十进制: 10
echo decoct(10) . "\n"; // 十进制转八进制: 12
echo octdec("12") . "\n"; // 八进制转十进制: 10
echo dechex(255) . "\n"; // 十进制转十六进制: ff
echo hexdec("ff") . "\n"; // 十六进制转十进制: 255
echo base_convert("1010", 2, 10) . "\n"; // 任意进制转换: 10
?>
5.3 文件系统操作
PHP
<?php
// ========== 文件读写 ==========
// 写入文件
file_put_contents("test.txt", "Hello, World!\n");
file_put_contents("test.txt", "Second line\n", FILE_APPEND);
file_put_contents("test.txt", "Third line\n", FILE_APPEND | LOCK_EX);
// 读取文件
$content = file_get_contents("test.txt");
echo $content;
// 逐行读取到数组
$lines = file("test.txt");
print_r($lines);
// 使用 fopen/fread/fwrite/fclose
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
// 写入
$handle = fopen("output.txt", "w");
fwrite($handle, "Some content\n");
fclose($handle);
// CSV读写
$handle = fopen("data.csv", "w");
fputcsv($handle, ["Name", "Age", "City"]);
fputcsv($handle, ["John", "30", "New York"]);
fputcsv($handle, ["Jane", "25", "London"]);
fclose($handle);
$handle = fopen("data.csv", "r");
$headers = fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
print_r(array_combine($headers, $row));
}
fclose($handle);
// ========== 文件信息 ==========
$filename = "test.txt";
echo file_exists($filename) . "\n"; // 文件是否存在
echo filesize($filename) . "\n"; // 文件大小(字节)
echo filemtime($filename) . "\n"; // 最后修改时间戳
echo filectime($filename) . "\n"; // 创建时间戳
echo fileatime($filename) . "\n"; // 最后访问时间戳
echo filetype($filename) . "\n"; // 文件类型: file/dir
echo is_readable($filename) . "\n"; // 是否可读
echo is_writable($filename) . "\n"; // 是否可写
echo is_executable($filename) . "\n"; // 是否可执行
echo is_file($filename) . "\n"; // 是否为文件
echo is_dir($filename) . "\n"; // 是否为目录
echo is_link($filename) . "\n"; // 是否为符号链接
// 获取路径信息
$pathinfo = pathinfo("/var/www/html/index.php");
print_r($pathinfo);
// ["dirname" => "/var/www/html", "basename" => "index.php",
// "extension" => "php", "filename" => "index"]
echo basename("/var/www/html/index.php") . "\n"; // index.php
echo dirname("/var/www/html/index.php") . "\n"; // /var/www/html
echo realpath("test.txt") . "\n"; // 绝对路径
// ========== 目录操作 ==========
// 创建目录
mkdir("new_folder", 0755, true); // true: 递归创建父目录
// 删除目录
rmdir("empty_folder");
// 读取目录
$files = scandir(".");
print_r($files);
// 使用 DirectoryIterator
$iterator = new DirectoryIterator(".");
foreach ($iterator as $fileInfo) {
if ($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "\n";
}
// 递归遍历目录
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(".", RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
echo $file->getPathname() . "\n";
}
// 使用 glob 匹配文件
$phpFiles = glob("*.php");
$allFiles = glob("*.*");
$matchedFiles = glob("src/**/*.php"); // 需要 GLOB_BRACE 标志
// ========== 文件操作 ==========
// 复制文件
copy("source.txt", "destination.txt");
// 移动/重命名文件
rename("old_name.txt", "new_name.txt");
// 删除文件
unlink("file_to_delete.txt");
// 创建符号链接
symlink("target.txt", "link.txt");
// 读取符号链接目标
echo readlink("link.txt") . "\n";
// 修改权限
chmod("test.txt", 0644);
// 修改所有者
chown("test.txt", "www-data");
// 修改所属组
chgrp("test.txt", "www-data");
// 创建临时文件
$tmpFile = tmpfile(); // 返回资源,关闭时自动删除
fwrite($tmpFile, "temporary data");
fclose($tmpFile);
// 获取临时文件名
$tmpPath = tempnam(sys_get_temp_dir(), "prefix_");
echo $tmpPath . "\n";
?>
5.4 过滤器与验证
PHP
<?php
// ========== filter_var: 过滤单个变量 ==========
// 验证
$email = "user@example.com";
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL)); // "user@example.com"
var_dump(filter_var("invalid", FILTER_VALIDATE_EMAIL)); // false
$ip = "192.168.1.1";
var_dump(filter_var($ip, FILTER_VALIDATE_IP)); // "192.168.1.1"
var_dump(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)); // IPv4
$url = "https://example.com";
var_dump(filter_var($url, FILTER_VALIDATE_URL)); // "https://example.com"
$int = "123";
var_dump(filter_var($int, FILTER_VALIDATE_INT)); // 123
var_dump(filter_var("abc", FILTER_VALIDATE_INT)); // false
$bool = "true";
var_dump(filter_var($bool, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
// 范围验证
$age = 25;
var_dump(filter_var($age, FILTER_VALIDATE_INT, [
"options" => ["min_range" => 0, "max_range" => 120],
])); // 25
// 正则验证
var_dump(filter_var("abc123", FILTER_VALIDATE_REGEXP, [
"options" => ["regexp" => "/^[a-z0-9]+$/"],
])); // "abc123"
// ========== 过滤(清理)==========
// 清理字符串
$input = "<script>alert('xss')</script>";
echo filter_var($input, FILTER_SANITIZE_STRING) . "\n"; // 移除HTML标签
// 清理Email(移除非法字符)
$email = "user()@example.com";
echo filter_var($email, FILTER_SANITIZE_EMAIL) . "\n"; // user@example.com
// 清理URL
$url = "https://example.com/path?query=test#frag";
echo filter_var($url, FILTER_SANITIZE_URL) . "\n";
// 清理整数
$num = "123abc";
echo filter_var($num, FILTER_SANITIZE_NUMBER_INT) . "\n"; // 123
// 清理浮点数
$float = "12.34abc";
echo filter_var($float, FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION) . "\n"; // 12.34
// ========== filter_input: 过滤输入变量 ==========
// 过滤GET参数
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
$name = filter_input(INPUT_GET, "name", FILTER_SANITIZE_STRING);
// 过滤POST参数
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, "age", FILTER_VALIDATE_INT, [
"options" => ["min_range" => 0, "max_range" => 120],
]);
// ========== filter_input_array: 批量过滤 ==========
$args = [
"username" => FILTER_SANITIZE_STRING,
"email" => FILTER_VALIDATE_EMAIL,
"age" => [
"filter" => FILTER_VALIDATE_INT,
"options" => ["min_range" => 0, "max_range" => 120],
],
];
$result = filter_input_array(INPUT_POST, $args);
?>
5.5 JSON 处理
PHP
<?php
// ========== json_encode: 编码 ==========
$data = [
"name" => "John",
"age" => 30,
"city" => "New York",
"hobbies" => ["reading", "gaming"],
"active" => true,
"score" => null,
];
// 基本编码
echo json_encode($data) . "\n";
// {"name":"John","age":30,"city":"New York","hobbies":["reading","gaming"],"active":true,"score":null}
// 美化输出
echo json_encode($data, JSON_PRETTY_PRINT) . "\n";
// 中文不转义
echo json_encode($data, JSON_UNESCAPED_UNICODE) . "\n";
// 组合选项
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
// 常用选项
// JSON_PRETTY_PRINT - 美化输出
// JSON_UNESCAPED_UNICODE - 不转义Unicode
// JSON_UNESCAPED_SLASHES - 不转义斜杠
// JSON_NUMERIC_CHECK - 将数字字符串转为数字
// JSON_FORCE_OBJECT - 强制输出对象
// JSON_THROW_ON_ERROR - 出错时抛出异常(PHP 7.3+)
// JSON_INVALID_UTF8_SUBSTITUTE - 替换无效UTF-8(PHP 7.2+)
// 错误处理
$result = json_encode($data);
if ($result === false) {
echo "JSON Error: " . json_last_error_msg() . "\n";
}
// ========== json_decode: 解码 ==========
$json = '{"name":"John","age":30,"city":"New York"}';
// 解码为对象
$obj = json_decode($json);
echo $obj->name . "\n"; // John
// 解码为数组
$arr = json_decode($json, true);
echo $arr["name"] . "\n"; // John
// 深度限制
$arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// 错误处理
try {
$data = json_decode($invalidJson, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "JSON decode error: " . $e->getMessage() . "\n";
}
// ========== json_validate: 验证JSON(PHP 8.3+)==========
var_dump(json_validate('{"name":"John"}')); // true
var_dump(json_validate('{invalid}')); // false
// ========== 流式JSON编码 ==========
// 处理大数据时使用
$stream = fopen("large.json", "w");
fwrite($stream, "[\n");
$first = true;
foreach ($largeData as $item) {
if (!$first) {
fwrite($stream, ",\n");
}
fwrite($stream, json_encode($item));
$first = false;
}
fwrite($stream, "\n]");
fclose($stream);
?>
六、数据库操作
6.1 PDO详解
PHP
<?php
// ========== PDO连接 ==========
$host = "localhost";
$dbname = "myapp";
$username = "root";
$password = "secret";
$charset = "utf8mb4";
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // 异常模式
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 默认关联数组
PDO::ATTR_EMULATE_PREPARES => false, // 使用原生预处理
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset", // 设置字符集
];
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// ========== 查询操作 ==========
// 查询所有记录
$stmt = $pdo->query("SELECT id, name, email FROM users");
$users = $stmt->fetchAll();
foreach ($users as $user) {
echo "{$user['id']}: {$user['name']} - {$user['email']}\n";
}
// 查询单条记录
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$user = $stmt->fetch();
// 获取单列
$stmt = $pdo->query("SELECT name FROM users");
$names = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($names);
// 获取键值对
$stmt = $pdo->query("SELECT id, name FROM users");
$users = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
// 获取对象
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$user = $stmt->fetch(PDO::FETCH_OBJ);
echo $user->name . "\n";
// 获取指定类的实例
class User {
public int $id;
public string $name;
public string $email;
}
$stmt = $pdo->query("SELECT id, name, email FROM users");
$user = $stmt->fetch(PDO::FETCH_CLASS, User::class);
// 行数统计
$stmt = $pdo->query("SELECT COUNT(*) FROM users");
$count = $stmt->fetchColumn();
echo "Total users: $count\n";
// ========== 预处理语句(防止SQL注入)==========
// 命名占位符
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(["email" => "john@example.com"]);
$user = $stmt->fetch();
// 问号占位符
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND status = ?");
$stmt->execute([18, "active"]);
$users = $stmt->fetchAll();
// bindValue(绑定固定值)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindValue(":id", 1, PDO::PARAM_INT);
$stmt->execute();
// bindParam(绑定变量引用)
$id = 1;
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$stmt->execute();
// ========== 插入操作 ==========
$stmt = $pdo->prepare(
"INSERT INTO users (name, email, age, created_at) VALUES (:name, :email, :age, NOW())"
);
$stmt->execute([
"name" => "John Doe",
"email" => "john@example.com",
"age" => 30,
]);
$lastId = $pdo->lastInsertId();
echo "Inserted ID: $lastId\n";
// 批量插入
$stmt = $pdo->prepare(
"INSERT INTO users (name, email, age) VALUES (:name, :email, :age)"
);
$users = [
["name" => "Alice", "email" => "alice@example.com", "age" => 25],
["name" => "Bob", "email" => "bob@example.com", "age" => 28],
["name" => "Charlie", "email" => "charlie@example.com", "age" => 35],
];
foreach ($users as $user) {
$stmt->execute($user);
}
// ========== 更新操作 ==========
$stmt = $pdo->prepare(
"UPDATE users SET name = :name, age = :age WHERE id = :id"
);
$stmt->execute([
"name" => "John Updated",
"age" => 31,
"id" => $lastId,
]);
echo "Rows affected: " . $stmt->rowCount() . "\n";
// ========== 删除操作 ==========
$stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$stmt->execute(["id" => $lastId]);
// ========== 事务处理 ==========
try {
$pdo->beginTransaction();
// 从账户A扣款
$stmt = $pdo->prepare(
"UPDATE accounts SET balance = balance - :amount WHERE id = :id"
);
$stmt->execute(["amount" => 100, "id" => 1]);
// 向账户B存款
$stmt->execute(["amount" => 100, "id" => 2]);
$pdo->commit();
echo "Transaction committed\n";
} catch (Exception $e) {
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage() . "\n";
}
// 嵌套事务(使用保存点模拟)
try {
$pdo->beginTransaction();
// 操作1
$pdo->exec("INSERT INTO logs (message) VALUES ('step 1')");
// 创建保存点
$pdo->exec("SAVEPOINT sp1");
try {
// 操作2(可能失败)
$pdo->exec("INSERT INTO users (name) VALUES ('test')");
} catch (Exception $e) {
// 回滚到保存点
$pdo->exec("ROLLBACK TO SAVEPOINT sp1");
}
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}
?>
6.2 MySQLi扩展
PHP
<?php
// ========== MySQLi面向对象方式 ==========
$mysqli = new mysqli("localhost", "root", "password", "myapp");
// 检查连接
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
}
// 设置字符集
$mysqli->set_charset("utf8mb4");
// 查询
$result = $mysqli->query("SELECT id, name, email FROM users");
while ($row = $result->fetch_assoc()) {
echo "{$row['id']}: {$row['name']}\n";
}
$result->free();
// 预处理语句
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$email = "john@example.com";
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
// 插入
$stmt = $mysqli->prepare(
"INSERT INTO users (name, email, age) VALUES (?, ?, ?)"
);
$stmt->bind_param("ssi", $name, $email, $age);
$name = "John";
$email = "john@example.com";
$age = 30;
$stmt->execute();
$lastId = $mysqli->insert_id;
// 关闭连接
$mysqli->close();
?>
七、Web开发
7.1 表单处理
PHP
<?php
// ========== 获取表单数据 ==========
// GET请求
$search = $_GET["q"] ?? "";
$page = $_GET["page"] ?? 1;
// POST请求
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$username = $_POST["username"] ?? "";
$password = $_POST["password"] ?? "";
$remember = isset($_POST["remember"]);
// 文件上传
$uploadedFile = $_FILES["avatar"] ?? null;
}
// 获取原始请求体
$rawInput = file_get_contents("php://input");
$jsonData = json_decode($rawInput, true);
// ========== 表单验证 ==========
function validateRegistration(array $data): array
{
$errors = [];
// 用户名验证
$username = trim($data["username"] ?? "");
if ($username === "") {
$errors["username"] = "用户名不能为空";
} elseif (strlen($username) < 3 || strlen($username) > 20) {
$errors["username"] = "用户名长度需在3-20个字符之间";
} elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
$errors["username"] = "用户名只能包含字母、数字和下划线";
}
// 邮箱验证
$email = trim($data["email"] ?? "");
if ($email === "") {
$errors["email"] = "邮箱不能为空";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "邮箱格式不正确";
}
// 密码验证
$password = $data["password"] ?? "";
if (strlen($password) < 8) {
$errors["password"] = "密码长度不能少于8个字符";
} elseif (!preg_match('/[A-Z]/', $password)) {
$errors["password"] = "密码需包含大写字母";
} elseif (!preg_match('/[a-z]/', $password)) {
$errors["password"] = "密码需包含小写字母";
} elseif (!preg_match('/[0-9]/', $password)) {
$errors["password"] = "密码需包含数字";
}
// 确认密码
$confirmPassword = $data["confirm_password"] ?? "";
if ($password !== $confirmPassword) {
$errors["confirm_password"] = "两次密码输入不一致";
}
// 年龄验证
$age = $data["age"] ?? "";
if ($age !== "") {
$age = filter_var($age, FILTER_VALIDATE_INT, [
"options" => ["min_range" => 0, "max_range" => 150],
]);
if ($age === false) {
$errors["age"] = "年龄不合法";
}
}
return $errors;
}
// CSRF保护
session_start();
if ($_SERVER["REQUEST_METHOD"] === "GET") {
// 生成CSRF Token
$_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// 验证CSRF Token
$submittedToken = $_POST["csrf_token"] ?? "";
$storedToken = $_SESSION["csrf_token"] ?? "";
if (!hash_equals($storedToken, $submittedToken)) {
die("CSRF token validation failed");
}
}
?>
<!DOCTYPE html>
<html>
<head><title>Registration Form</title></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<label>用户名: <input type="text" name="username" required></label><br>
<label>邮箱: <input type="email" name="email" required></label><br>
<label>密码: <input type="password" name="password" required></label><br>
<label>确认密码: <input type="password" name="confirm_password" required></label><br>
<label>年龄: <input type="number" name="age" min="0" max="150"></label><br>
<label>头像: <input type="file" name="avatar" accept="image/*"></label><br>
<button type="submit">注册</button>
</form>
</body>
</html>
7.2 文件上传
PHP
<?php
// ========== 文件上传处理 ==========
function handleFileUpload(array $file, string $uploadDir = "uploads/"): array
{
// 检查上传错误
if ($file["error"] !== UPLOAD_ERR_OK) {
$errorMessages = [
UPLOAD_ERR_INI_SIZE => "文件大小超过php.ini限制",
UPLOAD_ERR_FORM_SIZE => "文件大小超过表单限制",
UPLOAD_ERR_PARTIAL => "文件部分上传",
UPLOAD_ERR_NO_FILE => "没有文件上传",
UPLOAD_ERR_NO_TMP_DIR => "缺少临时目录",
UPLOAD_ERR_CANT_WRITE => "写入磁盘失败",
UPLOAD_ERR_EXTENSION => "扩展阻止了上传",
];
return ["error" => $errorMessages[$file["error"]] ?? "未知上传错误"];
}
// 验证文件大小(最大5MB)
$maxSize = 5 * 1024 * 1024;
if ($file["size"] > $maxSize) {
return ["error" => "文件大小不能超过5MB"];
}
// 验证MIME类型
$allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp"];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file["tmp_name"]);
finfo_close($finfo);
if (!in_array($mimeType, $allowedTypes)) {
return ["error" => "不支持的文件类型: $mimeType"];
}
// 验证文件扩展名
$allowedExtensions = ["jpg", "jpeg", "png", "gif", "webp"];
$extension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions)) {
return ["error" => "不支持的文件扩展名: $extension"];
}
// 创建上传目录
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// 生成唯一文件名
$newFilename = bin2hex(random_bytes(16)) . "." . $extension;
$destination = $uploadDir . $newFilename;
// 移动文件
if (!move_uploaded_file($file["tmp_name"], $destination)) {
return ["error" => "文件保存失败"];
}
return [
"success" => true,
"filename" => $newFilename,
"original_name" => $file["name"],
"size" => $file["size"],
"mime_type" => $mimeType,
"path" => $destination,
];
}
// 使用示例
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["avatar"])) {
$result = handleFileUpload($_FILES["avatar"]);
if (isset($result["error"])) {
echo "Upload failed: " . $result["error"] . "\n";
} else {
echo "Upload successful: " . $result["path"] . "\n";
}
}
?>
7.3 会话管理
PHP
<?php
// ========== Session 配置 ==========
// 在 session_start() 之前配置
ini_set("session.cookie_lifetime", "86400"); // Cookie有效期:24小时
ini_set("session.gc_maxlifetime", "86400"); // 垃圾回收最大生命周期
ini_set("session.cookie_httponly", "1"); // 仅HTTP访问
ini_set("session.cookie_secure", "1"); // 仅HTTPS
ini_set("session.cookie_samesite", "Lax"); // SameSite属性
ini_set("session.use_strict_mode", "1"); // 严格模式
ini_set("session.use_only_cookies", "1"); // 仅使用Cookie
// ========== Session 基本操作 ==========
session_start();
// 设置会话变量
$_SESSION["user_id"] = 123;
$_SESSION["username"] = "john";
$_SESSION["role"] = "admin";
$_SESSION["login_time"] = time();
// 访问会话变量
if (isset($_SESSION["user_id"])) {
echo "Logged in as: " . $_SESSION["username"] . "\n";
}
// 检查登录状态
function isLoggedIn(): bool
{
return isset($_SESSION["user_id"]);
}
function requireLogin(): void
{
if (!isLoggedIn()) {
header("Location: /login.php");
exit;
}
}
// 会话ID重新生成(防止会话固定攻击)
function regenerateSession(): void
{
session_regenerate_id(true); // true: 删除旧会话文件
}
// 登录时重新生成
if ($loginSuccessful) {
session_regenerate_id(true);
$_SESSION["user_id"] = $user["id"];
}
// 删除会话变量
unset($_SESSION["temp_data"]);
// 销毁整个会话
session_destroy();
// ========== Session 安全 ==========
// 设置会话过期时间
function checkSessionTimeout(): void
{
$maxIdleTime = 1800; // 30分钟
if (isset($_SESSION["last_activity"]) &&
(time() - $_SESSION["last_activity"] > $maxIdleTime)) {
session_unset();
session_destroy();
header("Location: /login.php?expired=1");
exit;
}
$_SESSION["last_activity"] = time();
}
// ========== Flash消息(一次性消息)==========
function setFlashMessage(string $type, string $message): void
{
$_SESSION["flash"][] = compact("type", "message");
}
function getFlashMessages(): array
{
$messages = $_SESSION["flash"] ?? [];
unset($_SESSION["flash"]);
return $messages;
}
setFlashMessage("success", "操作成功!");
setFlashMessage("error", "请检查输入数据");
foreach (getFlashMessages() as $msg) {
echo "<div class='alert alert-{$msg['type']}'>{$msg['message']}</div>\n";
}
?>
7.4 Cookie操作
PHP
<?php
// ========== 设置Cookie ==========
// 基本Cookie(1小时有效)
setcookie("username", "john", time() + 3600, "/");
// 完整参数
setcookie(
"remember_token", // 名称
$token, // 值
time() + 86400 * 30, // 过期时间(30天)
"/", // 路径
"", // 域名
true, // Secure(仅HTTPS)
true // HttpOnly(禁止JS访问)
);
// PHP 7.3+ 支持 SameSite
setcookie("session", $value, [
"expires" => time() + 86400,
"path" => "/",
"domain" => "",
"secure" => true,
"httponly" => true,
"samesite" => "Lax", // None, Lax, Strict
]);
// ========== 读取Cookie ==========
$username = $_COOKIE["username"] ?? "Guest";
$token = $_COOKIE["remember_token"] ?? null;
// ========== 删除Cookie ==========
// 设置过期时间为过去
setcookie("username", "", time() - 3600, "/");
// ========== 记住我功能 ==========
function generateRememberToken(): string
{
return bin2hex(random_bytes(32));
}
// 登录时设置
if ($rememberMe) {
$token = generateRememberToken();
$hashedToken = hash("sha256", $token);
$expires = time() + 86400 * 30;
// 保存到数据库
$stmt = $pdo->prepare(
"INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?, ?, ?)"
);
$stmt->execute([$user["id"], $hashedToken, date("Y-m-d H:i:s", $expires)]);
// 设置Cookie
setcookie("remember_token", $token, $expires, "/", "", true, true);
}
// 自动登录检查
function autoLoginFromCookie(): void
{
$token = $_COOKIE["remember_token"] ?? null;
if ($token === null) return;
$hashedToken = hash("sha256", $token);
$stmt = $pdo->prepare(
"SELECT user_id FROM remember_tokens WHERE token_hash = ? AND expires_at > NOW()"
);
$stmt->execute([$hashedToken]);
$result = $stmt->fetch();
if ($result) {
// 自动登录
$_SESSION["user_id"] = $result["user_id"];
session_regenerate_id(true);
}
}
?>
7.5 HTTP请求与响应
PHP
<?php
// ========== 发送HTTP头 ==========
// 重定向
header("Location: /dashboard.php");
exit; // 重要:重定向后必须exit
// 设置状态码
header("HTTP/1.1 404 Not Found");
http_response_code(404);
// 设置内容类型
header("Content-Type: application/json; charset=utf-8");
// 文件下载
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"download.pdf\"");
header("Content-Length: " . filesize("file.pdf"));
readfile("file.pdf");
// 缓存控制
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
// CORS头
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
// 设置多个头
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
// ========== 获取请求信息 ==========
// 请求方法
echo $_SERVER["REQUEST_METHOD"] . "\n"; // GET, POST, PUT, DELETE
// 请求URI
echo $_SERVER["REQUEST_URI"] . "\n"; // /path?query=value
// 客户端IP
echo $_SERVER["REMOTE_ADDR"] . "\n";
// User Agent
echo $_SERVER["HTTP_USER_AGENT"] . "\n";
// 引用页
echo $_SERVER["HTTP_REFERER"] ?? "" . "\n";
// 获取所有请求头
$headers = getallheaders();
print_r($headers);
// 判断是否为AJAX请求
function isAjax(): bool
{
return isset($_SERVER["HTTP_X_REQUESTED_WITH"])
&& strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest";
}
// 判断是否为HTTPS
function isHttps(): bool
{
return (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off")
|| $_SERVER["SERVER_PORT"] == 443;
}
// ========== JSON API 响应 ==========
function jsonResponse(array $data, int $statusCode = 200): void
{
http_response_code($statusCode);
header("Content-Type: application/json; charset=utf-8");
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
}
// 成功响应
jsonResponse(["success" => true, "data" => $result]);
// 错误响应
jsonResponse(["error" => "Not Found", "message" => "Resource not found"], 404);
// ========== 输出缓冲 ==========
ob_start(); // 开始输出缓冲
echo "Some output";
$content = ob_get_clean(); // 获取并清除缓冲区
// 模板渲染
function render(string $template, array $data = []): string
{
extract($data);
ob_start();
include $template;
return ob_get_clean();
}
?>
八、网络编程与cURL
8.1 cURL详解
PHP
<?php
// ========== GET请求 ==========
function httpGet(string $url, array $headers = []): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$errno = curl_errno($ch);
curl_close($ch);
return [
"status_code" => $httpCode,
"body" => $response,
"error" => $error,
"errno" => $errno,
];
}
// ========== POST请求 ==========
function httpPost(string $url, array $data, array $headers = []): array
{
$ch = curl_init();
$defaultHeaders = ["Content-Type: application/json"];
$headers = array_merge($defaultHeaders, $headers);
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
return [
"status_code" => $httpCode,
"body" => $response,
"error" => $error,
];
}
// ========== 表单POST请求 ==========
function httpPostForm(string $url, array $formData): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($formData),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ["status_code" => $httpCode, "body" => $response];
}
// ========== 文件上传 ==========
function httpUploadFile(string $url, string $filePath, array $formData = []): array
{
$ch = curl_init();
$postFields = $formData;
$postFields["file"] = new CURLFile($filePath);
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
]);
$response = curl_exec($ch);
curl_close($ch);
return ["body" => $response];
}
// ========== PUT/DELETE请求 ==========
function httpPut(string $url, array $data): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ["status_code" => $httpCode, "body" => $response];
}
function httpDelete(string $url): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "DELETE",
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ["status_code" => $httpCode, "body" => $response];
}
// ========== 带认证的请求 ==========
function httpGetWithBasicAuth(string $url, string $username, string $password): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => "$username:$password",
]);
$response = curl_exec($ch);
curl_close($ch);
return ["body" => $response];
}
function httpGetWithBearerToken(string $url, string $token): array
{
return httpGet($url, ["Authorization: Bearer $token"]);
}
// ========== 获取响应信息 ==========
$ch = curl_init("https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$info = curl_getinfo($ch);
echo "URL: " . $info["url"] . "\n";
echo "HTTP Code: " . $info["http_code"] . "\n";
echo "Total Time: " . $info["total_time"] . "s\n";
echo "Size: " . $info["size_download"] . " bytes\n";
echo "Content Type: " . $info["content_type"] . "\n";
curl_close($ch);
// ========== 多并发cURL请求 ==========
function multiHttpRequests(array $urls): array
{
$multiHandle = curl_multi_init();
$curlHandles = [];
$results = [];
foreach ($urls as $key => $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_multi_add_handle($multiHandle, $ch);
$curlHandles[$key] = $ch;
}
// 执行所有请求
$running = null;
do {
curl_multi_exec($multiHandle, $running);
curl_multi_select($multiHandle);
} while ($running > 0);
// 获取结果
foreach ($curlHandles as $key => $ch) {
$results[$key] = curl_multi_getcontent($ch);
curl_multi_remove_handle($multiHandle, $ch);
}
curl_multi_close($multiHandle);
return $results;
}
?>
8.2 Socket编程
PHP
<?php
// ========== TCP Socket 客户端 ==========
function tcpClient(string $host, int $port, string $message): string
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
throw new \RuntimeException("Failed to create socket: " . socket_strerror(socket_last_error()));
}
// 连接
if (!socket_connect($socket, $host, $port)) {
throw new \RuntimeException("Failed to connect: " . socket_strerror(socket_last_error($socket)));
}
// 发送数据
socket_write($socket, $message, strlen($message));
// 接收响应
$response = socket_read($socket, 4096);
socket_close($socket);
return $response;
}
// ========== TCP Socket 服务端 ==========
function tcpServer(int $port): void
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, "0.0.0.0", $port);
socket_listen($socket, 5);
echo "Server listening on port $port\n";
while (true) {
$client = socket_accept($socket);
if ($client === false) continue;
$input = socket_read($client, 4096);
echo "Received: $input\n";
// 处理请求
$response = "HTTP/1.1 200 OK\r\n";
$response .= "Content-Type: text/plain\r\n";
$response .= "Connection: close\r\n\r\n";
$response .= "Hello, World!";
socket_write($client, $response, strlen($response));
socket_close($client);
}
socket_close($socket);
}
// ========== 流上下文(Stream Context)==========
// HTTP流上下文
$context = stream_context_create([
"http" => [
"method" => "POST",
"header" => "Content-Type: application/json\r\n" .
"Authorization: Bearer token123\r\n",
"content" => json_encode(["key" => "value"]),
"timeout" => 30,
"ignore_errors" => true,
],
]);
$response = file_get_contents("https://api.example.com/endpoint", false, $context);
// SSL流上下文
$sslContext = stream_context_create([
"ssl" => [
"verify_peer" => true,
"verify_peer_name" => true,
"allow_self_signed" => false,
"cafile" => "/path/to/cacert.pem",
],
]);
?>
九、错误处理与异常
9.1 异常处理
PHP
<?php
// ========== 基本异常处理 ==========
try {
// 可能抛出异常的代码
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Division by zero: " . $e->getMessage() . "\n";
} catch (\Throwable $e) {
echo "Error: " . $e->getMessage() . "\n";
echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
echo "Trace: " . $e->getTraceAsString() . "\n";
} finally {
// 总是执行的清理代码
echo "Cleanup done\n";
}
// ========== 自定义异常 ==========
class ValidationException extends \Exception
{
private array $errors;
public function __construct(string $message, array $errors = [], int $code = 0)
{
parent::__construct($message, $code);
$this->errors = $errors;
}
public function getErrors(): array
{
return $this->errors;
}
}
class DatabaseException extends \RuntimeException
{
private ?string $query;
private ?array $params;
public function __construct(
string $message,
?string $query = null,
?array $params = null,
int $code = 0,
\Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
$this->query = $query;
$this->params = $params;
}
public function getQuery(): ?string
{
return $this->query;
}
public function getParams(): ?array
{
return $this->params;
}
}
// 使用自定义异常
function validateUserData(array $data): void
{
$errors = [];
if (empty($data["name"])) {
$errors["name"] = "Name is required";
}
if (!empty($errors)) {
throw new ValidationException("Validation failed", $errors);
}
}
try {
validateUserData([]);
} catch (ValidationException $e) {
echo "Validation errors:\n";
foreach ($e->getErrors() as $field => $error) {
echo " $field: $error\n";
}
}
// ========== 全局异常处理器 ==========
set_exception_handler(function (\Throwable $e) {
// 记录日志
error_log("Uncaught exception: " . $e->getMessage());
error_log("Stack trace: " . $e->getTraceAsString());
// 返回友好的错误页面
if (php_sapi_name() === "cli") {
echo "Error: " . $e->getMessage() . "\n";
} else {
http_response_code(500);
echo json_encode([
"error" => "Internal Server Error",
"message" => $e->getMessage(),
]);
}
});
// ========== 全局错误处理器 ==========
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
// 将错误转换为异常
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// ========== 断言 ==========
// 开发环境开启断言
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_EXCEPTION, true); // PHP 7.0+ 抛出异常
try {
assert(1 === 2, "This assertion will fail");
} catch (\AssertionError $e) {
echo "Assertion failed: " . $e->getMessage() . "\n";
}
?>
9.2 日志记录
PHP
<?php
// ========== 基本日志 ==========
// 写入系统日志
error_log("Something went wrong");
// 写入文件
error_log("Error message\n", 3, "/var/log/myapp.log");
// 发送邮件
// error_log("Error message", 1, "admin@example.com");
// ========== 自定义日志类 ==========
class Logger
{
const DEBUG = 100;
const INFO = 200;
const WARNING = 300;
const ERROR = 400;
private static array $levelNames = [
self::DEBUG => "DEBUG",
self::INFO => "INFO",
self::WARNING => "WARNING",
self::ERROR => "ERROR",
];
public function __construct(
private string $logFile,
private int $minLevel = self::DEBUG,
) {}
public function debug(string $message, array $context = []): void
{
$this->log(self::DEBUG, $message, $context);
}
public function info(string $message, array $context = []): void
{
$this->log(self::INFO, $message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->log(self::WARNING, $message, $context);
}
public function error(string $message, array $context = []): void
{
$this->log(self::ERROR, $message, $context);
}
private function log(int $level, string $message, array $context = []): void
{
if ($level < $this->minLevel) {
return;
}
$levelName = self::$levelNames[$level] ?? "UNKNOWN";
$timestamp = date("Y-m-d H:i:s");
$contextStr = $context ? " " . json_encode($context) : "";
$entry = "[$timestamp] [$levelName] $message$contextStr" . PHP_EOL;
file_put_contents($this->logFile, $entry, FILE_APPEND | LOCK_EX);
}
}
$logger = new Logger("/var/log/myapp.log");
$logger->info("User logged in", ["user_id" => 123]);
$logger->error("Database connection failed", ["host" => "localhost"]);
?>
十、安全实践
10.1 密码安全
PHP
<?php
// ========== 密码哈希 ==========
// 使用 password_hash()(推荐)
$password = "user_password";
// 使用 bcrypt 算法(默认)
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash . "\n";
// $2y$10$... (60字符)
// 使用 bcrypt,指定成本因子
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
// 成本因子越高越安全,但越慢,建议10-12
// 使用 Argon2i(PHP 7.2+)
$hash = password_hash($password, PASSWORD_ARGON2I);
echo $hash . "\n";
// 使用 Argon2id(PHP 7.3+,推荐)
$hash = password_hash($password, PASSWORD_ARGON2ID, [
"memory_cost" => 65536, // 64MB
"time_cost" => 4,
"threads" => 3,
]);
// ========== 密码验证 ==========
if (password_verify($password, $hash)) {
echo "Password is valid!\n";
} else {
echo "Password is invalid!\n";
}
// ========== 检查是否需要重新哈希 ==========
// 如果算法或配置改变,需要重新哈希
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
// 保存新哈希到数据库
}
// ========== 获取密码哈希信息 ==========
$info = password_get_info($hash);
print_r($info);
// ["algo" => "bcrypt", "algoName" => "bcrypt", "options" => ["cost" => 10]]
?>
10.2 SQL注入防护
PHP
<?php
// ========== 使用预处理语句(推荐)==========
// PDO预处理
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(["username" => $input]);
$user = $stmt->fetch();
// MySQLi预处理
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $input);
$stmt->execute();
// ========== 动态表名/列名处理 ==========
// 预处理不支持表名和列名,必须手动验证
$allowedColumns = ["id", "name", "email", "created_at"];
$allowedDirections = ["ASC", "DESC"];
$column = $_GET["sort"] ?? "id";
if (!in_array($column, $allowedColumns)) {
$column = "id";
}
$direction = strtoupper($_GET["dir"] ?? "ASC");
if (!in_array($direction, $allowedDirections)) {
$direction = "ASC";
}
$query = "SELECT * FROM users ORDER BY $column $direction";
// 注意:表名和列名已通过白名单验证
// ========== 转义(不推荐,仅作备用)==========
// 使用 PDO::quote() 转义字符串
$escaped = $pdo->quote($input);
$query = "SELECT * FROM users WHERE name = $escaped";
// 使用 mysqli_real_escape_string()
$escaped = $mysqli->real_escape_string($input);
$query = "SELECT * FROM users WHERE name = '$escaped'";
?>
10.3 XSS防护
PHP
<?php
// ========== 输出转义 ==========
// htmlspecialchars:转义HTML特殊字符
$userInput = '<script>alert("xss")</script>';
echo htmlspecialchars($userInput, ENT_QUOTES, "UTF-8");
// <script>alert("xss")</script>
// 常用参数
// ENT_QUOTES - 转义单引号和双引号
// ENT_NOQUOTES - 不转义任何引号
// ENT_COMPAT - 仅转义双引号(默认)
// ========== 不同上下文的转义 ==========
// HTML上下文
echo htmlspecialchars($data, ENT_QUOTES, "UTF-8");
// HTML属性
echo '<div data-value="' . htmlspecialchars($data, ENT_QUOTES, "UTF-8") . '">';
// JavaScript上下文
$jsData = json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
echo "<script>var data = $jsData;</script>";
// URL上下文
echo '<a href="' . urlencode($url) . '">Link</a>';
// CSS上下文
// 尽量避免动态CSS,如需要则严格验证
// ========== 内容安全策略(CSP)==========
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-$nonce'; style-src 'self'");
?>
10.4 其他安全措施
PHP
<?php
// ========== CSRF防护 ==========
// 生成Token
function generateCsrfToken(): string
{
if (empty($_SESSION["csrf_token"])) {
$_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}
return $_SESSION["csrf_token"];
}
// 验证Token
function validateCsrfToken(string $token): bool
{
if (!isset($_SESSION["csrf_token"])) {
return false;
}
return hash_equals($_SESSION["csrf_token"], $token);
}
// 在表单中使用
$csrfToken = generateCsrfToken();
echo '<input type="hidden" name="csrf_token" value="' . $csrfToken . '">';
// 在POST请求中验证
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$token = $_POST["csrf_token"] ?? "";
if (!validateCsrfToken($token)) {
http_response_code(403);
die("CSRF validation failed");
}
}
// ========== 文件包含安全 ==========
// 白名单验证
$allowedPages = ["home", "about", "contact", "products"];
$page = $_GET["page"] ?? "home";
if (!in_array($page, $allowedPages)) {
$page = "home";
}
include "pages/{$page}.php";
// ========== 命令注入防护 ==========
// 使用 escapeshellcmd() 和 escapeshellarg()
$userInput = $_GET["filename"] ?? "";
$safeFilename = escapeshellarg($userInput);
$output = shell_exec("ls -la $safeFilename");
// ========== 敏感信息保护 ==========
// 不要在代码中硬编码密码
// 使用环境变量或配置文件
$dbPassword = getenv("DB_PASSWORD");
// 不要在日志中记录敏感信息
// 不要在错误消息中暴露敏感信息
// 生产环境关闭错误显示
ini_set("display_errors", "0");
ini_set("display_startup_errors", "0");
error_reporting(E_ALL);
ini_set("log_errors", "1");
// ========== 文件上传安全 ==========
// 使用白名单验证文件类型
// 生成随机文件名
// 限制文件大小
// 将上传目录放在Web根目录外
// 使用.htaccess限制上传
?>
十一、PHP 8.x 新特性
11.1 命名参数(PHP 8.0)
PHP
<?php
// 可以按名称传递参数,跳过可选参数
function createOrder(
string $product,
int $quantity,
float $price,
string $currency = "USD",
bool $giftWrap = false,
?string $note = null,
): array {
return compact("product", "quantity", "price", "currency", "giftWrap", "note");
}
// 使用命名参数,跳过可选参数
$order = createOrder(
product: "Laptop",
quantity: 1,
price: 999.99,
note: "Please deliver on weekend",
);
print_r($order);
?>
11.2 match 表达式(PHP 8.0)
PHP
<?php
// match 是严格的 === 比较,并且返回值
$httpCode = 404;
$message = match ($httpCode) {
200, 201, 204 => "Success",
301, 302 => "Redirect",
400 => "Bad Request",
401, 403 => "Unauthorized",
404 => "Not Found",
500, 502, 503 => "Server Error",
default => "Unknown",
};
echo $message . "\n"; // Not Found
// match 不需要 break,每个分支只支持单行表达式
$result = match (true) {
$score >= 90 => "A",
$score >= 80 => "B",
default => "F",
};
?>
11.3 Nullsafe 运算符(PHP 8.0)
PHP
<?php
class User {
public function __construct(
public ?Address $address = null,
) {}
public function getAddress(): ?Address {
return $this->address;
}
}
class Address {
public function __construct(
public ?string $city = null,
) {}
public function getCity(): ?string {
return $this->city;
}
}
// 传统方式:多层null检查
$user = new User(new Address("New York"));
$city = null;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$city = $address->getCity();
}
}
// Nullsafe运算符:链式调用,遇到null立即返回null
$city = $user?->getAddress()?->getCity();
echo $city . "\n"; // New York
// 没有地址的情况
$user2 = new User();
$city2 = $user2?->getAddress()?->getCity();
var_dump($city2); // NULL
?>
11.4 联合类型(PHP 8.0)
PHP
<?php
// 参数可以是多种类型之一
function formatValue(int|float $value): string {
return number_format($value, 2);
}
// 返回类型也可以是联合类型
function findUser(int $id): array|null {
// 查找用户...
return null;
}
// 多种类型组合
class Response {
public function getData(): array|string|int|null {
return null;
}
}
?>
11.5 构造器属性提升(PHP 8.0)
PHP
<?php
// 传统方式
class OldStyle {
private string $name;
private int $age;
private string $email;
public function __construct(string $name, int $age, string $email) {
$this->name = $name;
$this->age = $age;
$this->email = $email;
}
}
// PHP 8.0+ 构造器属性提升
class NewStyle {
public function __construct(
public string $name,
public int $age,
private string $email,
protected string $role = "user",
) {}
}
$obj = new NewStyle("John", 30, "john@example.com");
echo $obj->name . "\n"; // John
?>
11.6 枚举(PHP 8.1)
PHP
<?php
// 带值的枚举
enum OrderStatus: string
{
case PENDING = "pending";
case PROCESSING = "processing";
case SHIPPED = "shipped";
case DELIVERED = "delivered";
case CANCELLED = "cancelled";
public function label(): string
{
return match ($this) {
self::PENDING => "待处理",
self::PROCESSING => "处理中",
self::SHIPPED => "已发货",
self::DELIVERED => "已送达",
self::CANCELLED => "已取消",
};
}
public function isFinal(): bool
{
return in_array($this, [self::DELIVERED, self::CANCELLED]);
}
}
$status = OrderStatus::PROCESSING;
echo $status->value . "\n"; // processing
echo $status->label() . "\n"; // 处理中
var_dump($status->isFinal()); // false
// 枚举实现了接口
interface Colorful
{
public function color(): string;
}
enum Suit: string implements Colorful
{
case Hearts = "H";
case Diamonds = "D";
case Clubs = "C";
case Spades = "S";
public function color(): string
{
return match ($this) {
self::Hearts, self::Diamonds => "Red",
self::Clubs, self::Spades => "Black",
};
}
}
?>
11.7 readonly 属性与类(PHP 8.1/8.2)
PHP
<?php
// readonly 属性(PHP 8.1+):只能初始化一次
class UserDTO
{
public function __construct(
public readonly string $id,
public readonly string $name,
public readonly string $email,
public readonly DateTimeImmutable $createdAt = new DateTimeImmutable(),
) {}
// 不能在构造之外修改 readonly 属性
// public function setName(string $name): void {
// $this->name = $name; // 错误!
// }
}
// readonly 类(PHP 8.2+):所有属性自动 readonly
readonly class ConfigDTO
{
public function __construct(
public string $host,
public int $port,
public string $dbName,
public array $options = [],
) {}
}
$config = new ConfigDTO("localhost", 3306, "myapp");
// $config->host = "other"; // 错误:不能修改
echo $config->host . "\n"; // localhost
?>
11.8 Fiber(PHP 8.1+)
PHP
<?php
// Fiber 提供协作式多任务(轻量级协程)
$fiber = new Fiber(function (): void {
$value = Fiber::suspend("fiber start");
echo "Fiber resumed with: $value\n";
$value2 = Fiber::suspend("fiber middle");
echo "Fiber resumed with: $value2\n";
});
// 启动Fiber
$result1 = $fiber->start();
echo "Main got: $result1\n"; // Main got: fiber start
// 恢复Fiber
$result2 = $fiber->resume("hello");
echo "Main got: $result2\n"; // Main got: fiber middle
// 再次恢复
$fiber->resume("world");
// 输出: Fiber resumed with: hello
// 输出: Fiber resumed with: world
?>
十二、Composer包管理
12.1 Composer基础
BASH
# ========== 项目初始化 ==========
composer init
# 交互式创建 composer.json
# 或手动创建 composer.json
cat > composer.json << 'EOF'
{
"name": "myvendor/myproject",
"description": "A PHP project",
"type": "project",
"require": {
"php": ">=8.1"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
EOF
# ========== 安装依赖 ==========
# 安装生产依赖
composer require monolog/monolog
composer require guzzlehttp/guzzle:^7.0
composer require laravel/serializable-closure
# 安装开发依赖
composer require --dev phpunit/phpunit
composer require --dev phpstan/phpstan
composer require --dev friendsofphp/php-cs-fixer
# 根据 composer.lock 安装(生产环境推荐)
composer install --no-dev
# 更新依赖
composer update
composer update monolog/monolog # 更新单个包
# 移除依赖
composer remove monolog/monolog
# ========== 查看信息 ==========
composer show # 列出所有安装的包
composer show monolog/monolog # 查看特定包信息
composer outdated # 检查过时的包
composer diagnose # 诊断常见问题
12.2 composer.json详解
JSON
{
"name": "myvendor/myproject",
"description": "A sample PHP project",
"type": "project",
"keywords": ["php", "web"],
"license": "MIT",
"authors": [
{
"name": "Your Name",
"email": "your@email.com"
}
],
"require": {
"php": ">=8.1",
"monolog/monolog": "^3.0",
"guzzlehttp/guzzle": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "^10.0",
"phpstan/phpstan": "^1.10"
},
"suggest": {
"ext-redis": "For Redis caching support"
},
"autoload": {
"psr-4": {
"App\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit",
"lint": "php-cs-fixer fix --dry-run",
"check": "phpstan analyse src tests",
"build": [
"@test",
"@lint",
"@check"
]
},
"config": {
"optimize-autoloader": true,
"sort-packages": true,
"platform": {
"php": "8.1"
}
}
}
12.3 自动加载
PHP
<?php
// ========== PSR-4 自动加载 ==========
// 目录结构:
// src/
// Controllers/
// UserController.php
// Models/
// User.php
// Services/
// UserService.php
// require vendor/autoload.php
require_once __DIR__ . "/vendor/autoload.php";
// 自动加载后,可以直接使用命名空间类
use App\Controllers\UserController;
use App\Models\User;
use App\Services\UserService;
$controller = new UserController();
$user = new User();
$service = new UserService();
// ========== 自定义类映射(classmap)==========
// composer.json 中配置
// "autoload": {
// "classmap": ["src/legacy/", "lib/"]
// }
// ========== 文件自动加载 ==========
// composer.json 中配置
// "autoload": {
// "files": ["src/helpers.php"]
// }
// helpers.php 中的函数在每次请求时自动加载
// helpers.php 示例
function base_path(string $path = ""): string
{
return __DIR__ . "/../" . ltrim($path, "/");
}
?>
十三、PHP测试
13.1 PHPUnit基础
PHP
<?php
// ========== PHPUnit安装 ==========
// composer require --dev phpunit/phpunit
// ========== 基本测试类 ==========
use PHPUnit\Framework\TestCase;
class Calculator
{
public function add(int $a, int $b): int
{
return $a + $b;
}
public function divide(int $a, int $b): float
{
if ($b === 0) {
throw new \InvalidArgumentException("Division by zero");
}
return $a / $b;
}
public function average(array $numbers): float
{
if (empty($numbers)) {
return 0;
}
return array_sum($numbers) / count($numbers);
}
}
class CalculatorTest extends TestCase
{
private Calculator $calculator;
// 每个测试前执行
protected function setUp(): void
{
$this->calculator = new Calculator();
}
// 每个测试后执行
protected function tearDown(): void
{
// 清理资源
}
// 测试方法必须以 test 开头,或用 @test 注解
public function testAdd(): void
{
$result = $this->calculator->add(2, 3);
$this->assertEquals(5, $result);
$this->assertSame(5, $result);
}
public function testAddNegative(): void
{
$this->assertEquals(0, $this->calculator->add(-1, 1));
$this->assertEquals(-3, $this->calculator->add(-1, -2));
}
public function testDivide(): void
{
$this->assertEquals(2.5, $this->calculator->divide(5, 2));
$this->assertIsFloat($this->calculator->divide(5, 2));
}
public function testDivideByZero(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("Division by zero");
$this->calculator->divide(10, 0);
}
public function testAverage(): void
{
$this->assertEquals(2.0, $this->calculator->average([1, 2, 3]));
$this->assertEquals(0, $this->calculator->average([]));
$this->assertEquals(5.0, $this->calculator->average([5]));
}
// ========== 常用断言 ==========
public function testAssertions(): void
{
// 相等性断言
$this->assertEquals("expected", "expected"); // 宽松相等
$this->assertSame("expected", "expected"); // 严格相等(===)
$this->assertNotEquals("a", "b");
$this->assertNotSame(1, "1");
// 布尔断言
$this->assertTrue(true);
$this->assertFalse(false);
$this->assertNull(null);
$this->assertNotNull("value");
// 类型断言
$this->assertIsInt(42);
$this->assertIsString("hello");
$this->assertIsArray([1, 2]);
$this->assertIsFloat(3.14);
$this->assertIsBool(true);
$this->assertIsObject(new stdClass());
// 包含断言
$this->assertContains(3, [1, 2, 3]);
$this->assertNotContains(4, [1, 2, 3]);
$this->assertStringContainsString("hello", "hello world");
$this->assertArrayHasKey("name", ["name" => "John"]);
// 计数断言
$this->assertCount(3, [1, 2, 3]);
$this->assertNotEmpty([1]);
$this->assertEmpty([]);
// 比较断言
$this->assertGreaterThan(5, 10);
$this->assertGreaterThanOrEqual(5, 5);
$this->assertLessThan(5, 3);
$this->assertLessThanOrEqual(5, 5);
// 正则断言
$this->assertMatchesRegularExpression("/^[a-z]+$/", "hello");
// 文件断言
$this->assertFileExists("/path/to/file");
$this->assertDirectoryExists("/path/to/dir");
}
}
// ========== 数据提供器 ==========
class MathTest extends TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider(): array
{
return [
"adding zeros" => [0, 0, 0],
"zero plus one" => [0, 1, 1],
"one plus zero" => [1, 0, 1],
"one plus one" => [1, 1, 2],
"two plus three" => [2, 3, 5],
];
}
}
// ========== Mock/Stub ==========
interface UserRepository
{
public function find(int $id): ?array;
public function save(array $user): bool;
}
class UserService
{
public function __construct(private UserRepository $repository) {}
public function getUserName(int $id): string
{
$user = $this->repository->find($id);
return $user["name"] ?? "Unknown";
}
}
class UserServiceTest extends TestCase
{
public function testGetUserName(): void
{
// 创建 Mock
$mock = $this->createMock(UserRepository::class);
// 配置 Mock 行为
$mock->method("find")
->with($this->equalTo(1))
->willReturn(["id" => 1, "name" => "John Doe"]);
$service = new UserService($mock);
$this->assertEquals("John Doe", $service->getUserName(1));
}
public function testGetUserNameNotFound(): void
{
$mock = $this->createMock(UserRepository::class);
$mock->method("find")->willReturn(null);
$service = new UserService($mock);
$this->assertEquals("Unknown", $service->getUserName(999));
}
}
?>
13.2 运行测试
BASH
# 运行所有测试
./vendor/bin/phpunit
# 运行指定测试文件
./vendor/bin/phpunit tests/CalculatorTest.php
# 运行指定测试方法
./vendor/bin/phpunit --filter testAdd
# 生成覆盖率报告
./vendor/bin/phpunit --coverage-html coverage/
# 生成代码覆盖率文本报告
./vendor/bin/phpunit --coverage-text
# PHPUnit配置文件 phpunit.xml
XML
<!-- phpunit.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
cacheDirectory=".phpunit.cache">
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="DB_DATABASE" value="test_db"/>
</php>
</phpunit>
十四、性能优化与最佳实践
14.1 性能优化
PHP
<?php
// ========== OPcache 配置 ==========
// php.ini
// opcache.enable=1
// opcache.memory_consumption=128
// opcache.interned_strings_buffer=8
// opcache.max_accelerated_files=10000
// opcache.validate_timestamps=0 // 生产环境关闭文件检查
// ========== 自动加载优化 ==========
// 生产环境生成优化的自动加载
// composer dump-autoload --optimize --no-dev
// --optimize: 生成classmap,比PSR-4更快
// --no-dev: 跳过开发依赖
// ========== 数据库查询优化 ==========
// 使用预处理语句(减少解析开销)
// 只查询需要的列,不使用 SELECT *
// 使用索引
// 使用 LIMIT 限制结果集
// 避免 N+1 查询问题
// 不好的做法
$users = $pdo->query("SELECT * FROM users")->fetchAll();
foreach ($users as $user) {
$posts = $pdo->query("SELECT * FROM posts WHERE user_id = {$user['id']}")->fetchAll();
// N+1 查询问题
}
// 好的做法:使用 JOIN 或 IN 查询
$users = $pdo->query("SELECT * FROM users")->fetchAll();
$userIds = array_column($users, "id");
$placeholders = implode(",", array_fill(0, count($userIds), "?"));
$stmt = $pdo->prepare("SELECT * FROM posts WHERE user_id IN ($placeholders)");
$stmt->execute($userIds);
$posts = $stmt->fetchAll();
// ========== 缓存策略 ==========
// 数据缓存
// 使用 APCu、Redis、Memcached
function getCachedData(string $key, callable $callback, int $ttl = 3600): mixed
{
// 检查APCu缓存
if (function_exists("apcu_exists") && apcu_exists($key)) {
return apcu_fetch($key);
}
// 获取数据
$data = $callback();
// 存入缓存
if (function_exists("apcu_store")) {
apcu_store($key, $data, $ttl);
}
return $data;
}
// 使用示例
$users = getCachedData("users_list", function () use ($pdo) {
return $pdo->query("SELECT id, name, email FROM users")->fetchAll();
}, 300);
// ========== 输出缓冲 ==========
// 开启输出缓冲,减少网络往返
ob_start("ob_gzhandler"); // 使用 gzip 压缩
// ========== 循环优化 ==========
// 将不变的计算移到循环外
$count = count($array); // 在循环前计算
for ($i = 0; $i < $count; $i++) {
// 处理
}
// 使用 foreach 比 for 更高效(对数组)
foreach ($array as $value) {
// 处理
}
// ========== 文件包含优化 ==========
// 使用绝对路径
include __DIR__ . "/config.php"; // 好
// include "config.php"; // 不好:需要搜索include_path
// ========== 内存优化 ==========
// 处理大文件时使用生成器
function readLargeFile(string $filename): Generator
{
$handle = fopen($filename, "r");
while (($line = fgets($handle)) !== false) {
yield trim($line);
}
fclose($handle);
}
// 对大数组使用迭代
foreach (readLargeFile("large.csv") as $line) {
processLine($line);
}
?>
14.2 编码最佳实践
PHP
<?php
// ========== 遵循 PSR 标准 ==========
// PSR-1: 基础编码标准
// PSR-4: 自动加载标准
// PSR-7: HTTP消息接口
// PSR-12: 扩展编码风格
// ========== 使用严格类型模式 ==========
declare(strict_types=1);
// ========== 使用类型声明 ==========
function processUser(int $id, string $action): ?array
{
// 明确的参数和返回类型
return null;
}
// ========== SOLID 原则 ==========
// 单一职责原则 (SRP): 一个类只做一件事
class UserRepository
{
public function find(int $id): ?array { /* ... */ }
public function save(array $user): int { /* ... */ }
public function delete(int $id): bool { /* ... */ }
}
class UserMailer
{
public function sendWelcome(User $user): void { /* ... */ }
public function sendPasswordReset(User $user): void { /* ... */ }
}
// 依赖注入 (DI): 通过构造器注入依赖
class UserController
{
public function __construct(
private UserRepository $repository,
private UserMailer $mailer,
) {}
public function register(array $data): array
{
$userId = $this->repository->save($data);
$user = $this->repository->find($userId);
$this->mailer->sendWelcome($user);
return $user;
}
}
// ========== 错误处理 ==========
// 抛出特定异常而非通用异常
class UserNotFoundException extends \RuntimeException {}
class InvalidCredentialsException extends \RuntimeException {}
class InsufficientBalanceException extends \RuntimeException {}
// ========== 避免全局状态 ==========
// 不好:使用全局变量
// global $config;
// function getDbConnection() {
// global $config;
// return new PDO($config["dsn"], ...);
// }
// 好:使用依赖注入
class Database
{
public function __construct(
private string $host,
private string $dbname,
private string $username,
private string $password,
) {}
public function connect(): PDO
{
return new PDO(
"mysql:host={$this->host};dbname={$this->dbname}",
$this->username,
$this->password,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
);
}
}
// ========== 使用不可变对象 ==========
class Money
{
public function __construct(
private readonly int $amount,
private readonly string $currency,
) {}
public function getAmount(): int { return $this->amount; }
public function getCurrency(): string { return $this->currency; }
public function add(self $other): self
{
if ($this->currency !== $other->currency) {
throw new \InvalidArgumentException("Currency mismatch");
}
return new self($this->amount + $other->amount, $this->currency);
}
}
// ========== 使用 Value Objects ==========
class Email
{
private function __construct(private readonly string $value) {}
public static function fromString(string $email): self
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException("Invalid email: $email");
}
return new self(strtolower($email));
}
public function getValue(): string { return $this->value; }
public function __toString(): string { return $this->value; }
}
// ========== 代码注释 ==========
/**
* 计算两个数的最大公约数(欧几里得算法)
*
* @param int $a 第一个正整数
* @param int $b 第二个正整数
* @return int 最大公约数
* @throws \InvalidArgumentException 如果参数不是正整数
*
* @example
* gcd(48, 18) => 6
*/
function gcd(int $a, int $b): int
{
if ($a <= 0 || $b <= 0) {
throw new \InvalidArgumentException("Both numbers must be positive");
}
while ($b != 0) {
$temp = $b;
$b = $a % $b;
$a = $temp;
}
return $a;
}
?>
十五、PHP框架简介
15.1 Laravel
PHP
<?php
// ========== 路由定义 ==========
// routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get("/", function () {
return view("welcome");
});
Route::get("/users", [UserController::class, "index"]);
Route::get("/users/{id}", [UserController::class, "show"]);
Route::post("/users", [UserController::class, "store"]);
Route::put("/users/{id}", [UserController::class, "update"]);
Route::delete("/users/{id}", [UserController::class, "destroy"]);
// 资源路由
Route::resource("posts", PostController::class);
// 路由组与中间件
Route::middleware(["auth", "verified"])->group(function () {
Route::get("/dashboard", DashboardController::class);
Route::resource("orders", OrderController::class);
});
// ========== 控制器 ==========
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class UserController extends Controller
{
public function index(): JsonResponse
{
$users = User::paginate(15);
return response()->json($users);
}
public function show(int $id): JsonResponse
{
$user = User::findOrFail($id);
return response()->json($user);
}
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
"name" => "required|string|max:255",
"email" => "required|email|unique:users",
"password" => "required|string|min:8",
]);
$validated["password"] = bcrypt($validated["password"]);
$user = User::create($validated);
return response()->json($user, 201);
}
}
// ========== Eloquent ORM ==========
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class User extends Model
{
protected $fillable = ["name", "email", "password"];
protected $hidden = ["password", "remember_token"];
protected $casts = [
"email_verified_at" => "datetime",
"is_active" => "boolean",
];
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function orders(): HasMany
{
return $this->hasMany(Order::class);
}
}
// 使用 Eloquent
// $users = User::where("active", true)->orderBy("name")->get();
// $user = User::find(1);
// $user->posts()->create(["title" => "New Post", "content" => "..."]);
// ========== Blade 模板 ==========
// resources/views/users/index.blade.php
/*
@extends("layouts.app")
@section("title", "Users")
@section("content")
<h1>Users</h1>
@foreach($users as $user)
<div>
<h2>{{ $user->name }}</h2>
<p>{{ $user->email }}</p>
</div>
@endforeach
{{ $users->links() }}
@endsection
*/
// ========== Artisan 命令 ==========
// php artisan make:model Product -m (创建模型和迁移)
// php artisan make:controller ProductController --resource
// php artisan make:middleware CheckRole
// php artisan migrate
// php artisan db:seed
// php artisan cache:clear
// php artisan config:cache (生产环境)
// php artisan route:cache (生产环境)
// php artisan view:cache (生产环境)
?>
15.2 Symfony
PHP
<?php
// ========== 控制器(属性路由)==========
// src/Controller/UserController.php
namespace App\Controller;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route("/api/users")]
class UserController extends AbstractController
{
#[Route("", methods: ["GET"])]
public function index(UserRepository $repository): JsonResponse
{
$users = $repository->findAll();
return $this->json($users);
}
#[Route("/{id}", methods: ["GET"])]
public function show(int $id, UserRepository $repository): JsonResponse
{
$user = $repository->find($id);
if (!$user) {
throw $this->createNotFoundException("User not found");
}
return $this->json($user);
}
#[Route("", methods: ["POST"])]
public function create(Request $request, UserRepository $repository): JsonResponse
{
$data = json_decode($request->getContent(), true);
$user = new User();
$user->setName($data["name"]);
$user->setEmail($data["email"]);
$repository->save($user, true);
return $this->json($user, Response::HTTP_CREATED);
}
}
// ========== Doctrine ORM ==========
// src/Entity/User.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: "users")]
class User
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255, unique: true)]
private ?string $email = null;
#[ORM\OneToMany(mappedBy: "user", targetEntity: Post::class)]
private Collection $posts;
public function __construct()
{
$this->posts = new ArrayCollection();
}
public function getId(): ?int { return $this->id; }
public function getName(): ?string { return $this->name; }
public function setName(string $name): self { $this->name = $name; return $this; }
public function getEmail(): ?string { return $this->email; }
public function setEmail(string $email): self { $this->email = $email; return $this; }
}
// ========== Twig 模板 ==========
// templates/users/index.html.twig
/*
{% extends "base.html.twig" %}
{% block title %}Users{% endblock %}
{% block body %}
<h1>Users</h1>
{% for user in users %}
<div>
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
</div>
{% endfor %}
{% endblock %}
*/
// ========== Symfony Console 命令 ==========
// php bin/console make:entity
// php bin/console make:controller
// php bin/console doctrine:migrations:migrate
// php bin/console cache:clear
?>
十六、总结
16.1 PHP优势总结
| 优势 | 说明 |
|---|---|
| Web开发首选 | 专为Web开发设计,与HTML、HTTP协议深度集成 |
| 部署简单 | 几乎所有主机商都支持,无需复杂配置 |
| 学习曲线平缓 | 语法简洁,适合初学者快速上手 |
| 生态丰富 | Composer包管理器、Laravel/Symfony等成熟框架 |
| 性能优异 | PHP 7+性能大幅提升,PHP 8引入JIT编译 |
| 类型系统增强 | PHP 7/8大幅增强类型系统,支持严格类型 |
| 社区活跃 | 丰富的文档、教程和开源项目 |
| 持续演进 | 每年发布新版本,持续引入现代语言特性 |
16.2 学习路径
CODE
PHP基础语法 → 数组与字符串 → 函数与OOP → 数据库操作 → 安全实践
↓ ↓ ↓ ↓ ↓
变量/类型 数组操作 类与对象 PDO/MySQLi 密码哈希
运算符 字符串函数 继承/接口 预处理语句 SQL注入/XSS
控制结构 正则表达式 Trait/魔术方法 事务处理 CSRF/会话
继续深入学习:
↓
Web开发完整流程 → 框架学习(Laravel/Symfony) → 测试与部署
↓
设计模式 → 架构设计 → 性能优化 → DevOps
16.3 推荐资源
| 资源 | 类型 | 链接 |
|---|---|---|
| PHP官方手册 | 文档 | https://www.php.net/manual/ |
| PHP The Right Way | 教程 | https://phptherightway.com/ |
| Laravel文档 | 框架 | https://laravel.com/docs |
| Symfony文档 | 框架 | https://symfony.com/doc |
| PHPUnit文档 | 测试 | https://phpunit.de/documentation.html |
| Composer文档 | 工具 | https://getcomposer.org/doc/ |
| PHP-FIG PSR标准 | 规范 | https://www.php-fig.org/psr/ |
| PHP安全手册 | 安全 | https://phpsecurity.readthedocs.io/ |
16.4 常用命令速查
BASH
# PHP内置服务器
php -S localhost:8000
# 查看PHP信息
php -i | grep -E "(php.ini|version|extension)"
# 语法检查
php -l file.php
# 运行脚本
php script.php
# Composer命令
composer install # 安装依赖
composer require vendor/pkg # 添加依赖
composer update # 更新依赖
composer dump-autoload -o # 优化自动加载
# PHPUnit
./vendor/bin/phpunit # 运行测试
./vendor/bin/phpunit --filter testMethod # 运行指定方法
./vendor/bin/phpunit --coverage-html coverage/ # 生成覆盖率
# 代码质量工具
./vendor/bin/phpstan analyse src tests --level=max
./vendor/bin/php-cs-fixer fix src
./vendor/bin/phpcs src --standard=PSR12
祝你通过本指南全面掌握PHP编程,成为一名高效的PHP开发者!