ZetCode

PHP never 关键字

最后修改于 2025 年 4 月 16 日

PHP never 返回类型表示一个永不返回的函数。它是在 PHP 8.1 中引入的。使用 never 类型的函数要么抛出异常,要么终止执行。这与 void 类型有所不同,void 类型会正常完成。

基本定义

never 类型代表不会将控制权返回给调用者的函数。这包括始终抛出异常或退出的函数。never 类型是 PHP 类型系统中的一个底部类型。

语法:function foo(): never { ... }。never 返回类型必须显式声明。使用 never 类型的函数不能有 return 语句。

主要特征:不允许返回值,必须终止执行,适用于致命错误或无限循环。它有助于静态分析工具。

基本 never 函数

此示例展示了一个始终抛出异常的简单函数。

basic_never.php
<?php

declare(strict_types=1);

function fail(string $message): never {
    throw new RuntimeException($message);
}

fail("Operation failed");

fail 函数声明了 never 返回类型。它总是抛出异常,从不正常返回。对 fail 的调用会终止执行。这是 never 的一个常见用例。

never 与 exit()

此示例演示了将 never 与 exit() 函数一起使用。

never_exit.php
<?php

declare(strict_types=1);

function shutdown(): never {
    echo "Shutting down...";
    exit(1);
}

shutdown();
echo "This will never be executed";

shutdown 函数调用 exit(),终止脚本。never 类型正确地表明了这种行为。shutdown() 调用之后的代码是不可达的。这有助于捕获逻辑错误。

never 在错误处理中

此示例展示了在错误处理场景中使用 never。

never_error.php
<?php

declare(strict_types=1);

function handleError(string $message): never {
    error_log($message);
    http_response_code(500);
    exit(1);
}

try {
    // Some operation that might fail
    throw new Exception("Database connection failed");
} catch (Exception $e) {
    handleError($e->getMessage());
}

handleError 函数记录错误并终止。never 类型清楚地传达了这种行为。这种模式在关键错误处理程序中很常见。它阻止了进一步的执行。

never 与无限循环

此示例演示了 never 与无限循环一起使用。

never_loop.php
<?php

declare(strict_types=1);

function runForever(): never {
    while (true) {
        echo "Running...\n";
        sleep(1);
    }
}

runForever();
echo "This line is unreachable";

runForever

never 在 Switch 默认情况下

此示例使用 never 用于详尽的 switch 语句。

never_switch.php
<?php

declare(strict_types=1);

function processStatus(string $status): string {
    return match ($status) {
        'success' => 'Operation succeeded',
        'pending' => 'Operation pending',
        default => throw new LogicException("Invalid status"),
    };
}

echo processStatus('success');

match 表达式在 default case 中使用 throw。这确保了所有情况都被处理。如果提取到单独的函数中,将使用 never 类型。这种模式强制进行详尽的匹配。

never 与类型检查

此示例展示了 never 如何与 PHP 的类型系统一起工作。

never_type.php
<?php

declare(strict_types=1);

function terminate(): never {
    exit(0);
}

function foo(): string {
    terminate();
    // No return needed because terminate() is never
}

echo foo();

foo 函数调用 terminate(),它永远不会返回。因此,foo 不需要 return 语句。PHP 知道 terminate() 之后的代码是不可达的。这有助于避免冗余代码。

never 在类方法中

此示例演示了类方法中的 never。

never_class.php
<?php

declare(strict_types=1);

class Auth {
    public function checkAccess(): never {
        if (!$this->isAuthenticated()) {
            header('Location: /login');
            exit();
        }
    }
    
    private function isAuthenticated(): bool {
        return false;
    }
}

$auth = new Auth();
$auth->checkAccess();
echo "Access granted";

checkAccess 方法在未通过身份验证时重定向。当身份验证失败时,它从不返回。never 类型记录了这种行为。这对于安全检查很有用。

最佳实践

来源

PHP never 文档

本教程通过实际示例介绍了 PHP never 返回类型,展示了它在各种场景中的用法,从错误处理到无限循环。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 PHP 教程