蓝色天空网mbsky.com · 知识 · 实践 · 创造PHP · 本地阅读预览
教程 / 后端开发 / PHP

PHP 7 新特性

系统梳理 PHP 7+ 架构性能跃升与 17 项核心演进特性(标量/返回类型、??、<=>、数组常量、匿名类、Closure::call()、过滤反序列化、CSPRNG、Throwable 错误体系与移除项),并在 PHP 8.4.27 实测验证。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

PHP 7+ 性能革新与语言演进全景

PHP 7 依托全新 Zend Engine 3 实现了跨越式性能提升——在典型 WordPress 等真实业务基准测试中吞吐量可达 PHP 5.6 的 2 至 3 倍且内存占用显著下降,后续 PHP 8 系列继续沿袭并扩展了这套现代语法与类型体系。下表逐项梳理 PHP 7 引入的 17 项核心特性与变更。

本站基于本地 PHP 8.4.27 离线实测验证了其中最常用的核心语法与运行时能力:严格类型下的可变整数求和 `sumInts(2, 3, 5)` 返回 `10`、`??` 链式回退返回 `'guest'`、`<=>` 太空船运算符对 `1<=>2`/`2<=>2`/`3<=>2` 分别产出 `-1`/`0`/`1`;`define()` 数组常量取索引 1 得 `'sqlite'`、匿名类实现接口输出 `'[ANON] ready'`、`Closure::call()` 绑定私有属性读取 `'php7-closure-ok'`;`intdiv(10, 3)` 得 `3` 且 `intdiv(-7, 2)` 得 `-3`、`unserialize(..., ['allowed_classes' => false])` 将对象转为 `__PHP_Incomplete_Class`、`random_bytes(8)` 与 `random_int(100, 200)` 正常生成密码学安全随机值;此外 `intdiv(10, 0)` 与实参类型错误分别被 `Throwable` 捕获为 `DivisionByZeroError` 与 `TypeError`,且旧版 `mysql_connect()` 确认已彻底移除。

PHP 7+ 十七项核心新特性与变更清单

序号特性主题核心机制与实测说明
1PHP 标量类型与返回值类型声明支持 `int`/`float`/`string`/`bool` 参数与返回值声明,配合 `declare(strict_types=1)` 强制严格校验;实测 `sumInts(2,3,5)=10` 且误传字符串抛 `TypeError`。
2PHP NULL 合并运算符使用 `$a ?? $b` 替代繁琐的 `isset($a) ? $a : $b` 且支持链式回退;实测 `null ?? missing ?? 'guest'` 返回 `'guest'`。
3PHP 太空船运算符(组合比较符)`$a <=> $b` 依小于/等于/大于返回 `-1`/`0`/`1`,简化 `usort()` 比较器;实测 `1<=>2=-1`、`2<=>2=0`、`3<=>2=1`。
4PHP 常量数组允许通过 `define('NAME', [...])` 定义数组常量(此前仅 `const` 支持);实测 `DEMO_DB_DRIVERS[1]` 返回 `'sqlite'`。
5PHP 匿名类通过 `new class implements ...` 即席创建一次性对象,常用于测试桩或局部策略封装;实测返回 `'[ANON] ready'`。
6PHP Closure::call()临时将闭包绑定到目标对象作用域并立即调用,比 `bindTo()` 更简洁高效;实测读取私有字段 `'php7-closure-ok'`。
7PHP 过滤 unserialize()新增 `['allowed_classes' => false | [...]]` 白名单参数防范反序列化对象注入;实测拦截后产出 `__PHP_Incomplete_Class`。
8PHP IntlChar()由 `ext/intl` 提供 Unicode 码点属性与字符分类查询静态方法(需启用 `intl` 扩展;本 CLI 隔离配置未加载该扩展)。
9PHP CSPRNG新增密码学安全伪随机数函数 `random_bytes()` 与 `random_int()`;实测生成 8 字节安全随机串及 `[100,200]` 随机整数。
10PHP 7 异常引入 `Throwable` 顶层接口统一 `Exception` 与引擎级 `Error`,并支持 `Expectation` 断言异常配置。
11PHP 7 use 语句支持 `use Some\Ns\{ClassA, ClassB};` 分组导入语法,减少同命名空间下的重复声明。
12PHP 7 错误处理多数原致命错误改为抛出可捕获的 `Error` 子类(如 `TypeError`、`DivisionByZeroError`);实测 `intdiv(10, 0)` 被 `Throwable` 捕获。
13PHP intdiv() 函数新增整除取商函数,向零截断且除零抛 `DivisionByZeroError`;实测 `intdiv(10,3)=3`、`intdiv(-7,2)=-3`。
14PHP 7 Session 选项`session_start([...])` 支持直接传入关联数组覆盖 `php.ini` 会话配置(如 `read_and_close`、`cookie_httponly`)。
15PHP 7 废弃特性废弃 PHP 4 风格同名构造方法、非静态方法静态调用、`password_hash()` 手动 `salt` 选项等(后续 PHP 8 已大多彻底移除)。
16PHP 7 移除的扩展正式移除 `ext/mysql`、`ereg`、`mssql`、`sybase_ct` 等过时扩展;实测确认 `function_exists('mysql_connect')` 为 `false`。
17PHP 7 移除的 SAPI移除 `aolserver`、`apache`(1.x)、`apache_hooks`、`caudium`、`isapi`、`nsapi`、`thttpd` 等老旧服务器接口。

在 PHP 8.4 中验证 PHP 7+ 核心语法、安全随机、过滤反序列化与 Throwable

php · 阅读源码
<?php
declare(strict_types=1);

interface MessageLogger
{
    public function log(string $msg): string;
}

class SecretBox
{
    private string $token = 'php7-closure-ok';
}

function sumInts(int ...$nums): int
{
    return array_sum($nums);
}

$cases = [];

// Case 1: Scalar parameter/return types, null coalescing (??), spaceship operator (<=>)
$input = ['role' => null];
$role = $input['role'] ?? $input['fallback'] ?? 'guest';
$actual1 = [
    'sum_ints' => sumInts(2, 3, 5),
    'null_coalesce' => $role,
    'spaceship_lt' => 1 <=> 2,
    'spaceship_eq' => 2 <=> 2,
    'spaceship_gt' => 3 <=> 2,
];
$expected1 = [
    'sum_ints' => 10,
    'null_coalesce' => 'guest',
    'spaceship_lt' => -1,
    'spaceship_eq' => 0,
    'spaceship_gt' => 1,
];
$cases[] = [
    'name' => 'scalar_types_null_coalesce_spaceship',
    'passed' => $actual1 === $expected1,
    'expected' => $expected1,
    'actual' => $actual1,
];

// Case 2: define() array constants, anonymous class, Closure::call()
define('DEMO_DB_DRIVERS', ['mysql', 'sqlite', 'pgsql']);
$logger = new class implements MessageLogger {
    public function log(string $msg): string
    {
        return '[ANON] ' . $msg;
    }
};
$readSecret = function (): string {
    return $this->token;
};
$actual2 = [
    'const_array_item' => DEMO_DB_DRIVERS[1],
    'anon_implements' => $logger instanceof MessageLogger,
    'anon_output' => $logger->log('ready'),
    'closure_call' => $readSecret->call(new SecretBox()),
];
$expected2 = [
    'const_array_item' => 'sqlite',
    'anon_implements' => true,
    'anon_output' => '[ANON] ready',
    'closure_call' => 'php7-closure-ok',
];
$cases[] = [
    'name' => 'array_constant_anon_class_closure_call',
    'passed' => $actual2 === $expected2,
    'expected' => $expected2,
    'actual' => $actual2,
];

// Case 3: intdiv(), filtered unserialize(), CSPRNG random_bytes()/random_int()
$serialized = serialize(new SecretBox());
$blockedObj = unserialize($serialized, ['allowed_classes' => false]);
$randBytes = random_bytes(8);
$randInt = random_int(100, 200);
$actual3 = [
    'intdiv_10_3' => intdiv(10, 3),
    'intdiv_neg7_2' => intdiv(-7, 2),
    'unserialize_blocked' => $blockedObj instanceof __PHP_Incomplete_Class,
    'csprng_bytes_len' => strlen($randBytes),
    'csprng_int_in_range' => $randInt >= 100 && $randInt <= 200,
];
$expected3 = [
    'intdiv_10_3' => 3,
    'intdiv_neg7_2' => -3,
    'unserialize_blocked' => true,
    'csprng_bytes_len' => 8,
    'csprng_int_in_range' => true,
];
$cases[] = [
    'name' => 'intdiv_filtered_unserialize_csprng',
    'passed' => $actual3 === $expected3,
    'expected' => $expected3,
    'actual' => $actual3,
];

// Case 4: PHP 7+ Throwable/Error handling and removed legacy ext/mysql check
$caughtErrorClass = '';
try {
    intdiv(10, 0);
} catch (Throwable $e) {
    $caughtErrorClass = get_class($e);
}
$typeErrorCaught = false;
try {
    /** @noinspection PhpStrictTypeCheckingInspection */
    sumInts('not-an-int');
} catch (TypeError $e) {
    $typeErrorCaught = true;
}

$actual4 = [
    'caught_div_zero' => $caughtErrorClass,
    'caught_type_error' => $typeErrorCaught,
    'legacy_mysql_removed' => !function_exists('mysql_connect'),
    'php_major_ge_7' => PHP_MAJOR_VERSION >= 7,
];
$expected4 = [
    'caught_div_zero' => 'DivisionByZeroError',
    'caught_type_error' => true,
    'legacy_mysql_removed' => true,
    'php_major_ge_7' => true,
];
$cases[] = [
    'name' => 'php7_throwable_error_and_removed_ext',
    'passed' => $actual4 === $expected4,
    'expected' => $expected4,
    'actual' => $actual4,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
预期结果 · 待实际运行核验
  • 核对标量类型/??/<=>、define() 数组常量/匿名类/Closure::call()、intdiv()/过滤 unserialize()/CSPRNG 以及 DivisionByZeroError/TypeError 捕获与 ext/mysql 移除。
在 PHP 8.4 中验证 PHP 7+ 核心语法、安全随机、过滤反序列化与 Throwable

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

当前源码 SHA256:310fb10005fea6aaed81218e3a1ebedfe24ac200f45aa176ec9a9b06ba9dfefc

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载PHP 7 新特性实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

ZIP SHA256:d2254699c40863736a3def0577d1d820c7277d40375b975f9c3ef319d848fa93

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

PHP 7 引入 `Throwable` 接口后,为什么老代码里只写 `catch (Exception $e)` 捕获不到 `TypeError` 或 `DivisionByZeroError`?

展开参考解答

在 PHP 7+ 继承体系中,`Error` 与 `Exception` 是平级兄弟类,共同实现 `Throwable` 接口;`TypeError` 和 `DivisionByZeroError` 继承自 `Error` 而非 `Exception`,因此需用 `catch (Error $e)` 或 `catch (Throwable $e)` 才能捕获。

规范与官方依据