ZetCode

PHP void 关键字

最后修改于 2025 年 4 月 16 日

PHP 的 void 关键字是一种返回类型声明,表示函数不返回任何值。 它在 PHP 7.1 中引入,有助于使代码更明确和可维护。 Void 函数执行操作,但不提供返回值。

基本定义

void 返回类型指定函数不返回任何内容。 它在参数列表之后的函数声明中使用。 Void 函数仍然可以使用 return 语句,但无需返回值。

Void 与返回 null 不同 - 它根本不意味着存在返回值。 尝试使用 void 函数的结果会导致严格模式下出现 TypeError。 Void 对于执行副作用而不进行计算的函数很有用。

语法:function name(params): void { code }。 必须显式声明 void 返回类型。 Void 函数不能用于期望值的表达式中。

基本 void 函数

此示例演示了一个简单的 void 函数,该函数打印一条消息。

basic_void.php
<?php

declare(strict_types=1);

function greet(string $name): void {
    echo "Hello, $name!";
}

greet("Alice");

greet 函数接受一个 name 参数,但不返回任何内容。 它执行一个动作(打印),但不产生返回值。 void 返回类型在函数签名中明确了这一点。

带有早期返回的 void 函数

此示例显示了一个使用 return 而没有值的 void 函数。

void_return.php
<?php

declare(strict_types=1);

function checkAge(int $age): void {
    if ($age < 18) {
        echo "Access denied.";
        return;
    }
    echo "Access granted.";
}

checkAge(20);

如果年龄小于 18 岁,则该函数会提前退出。 Void 函数可以使用空的 return 语句提前退出。 这与 void 返回类型不冲突,因为不返回任何值。

类方法中的 void

此示例演示了将 void 与类方法一起使用。

void_method.php
<?php

declare(strict_types=1);

class Logger {
    public function log(string $message): void {
        file_put_contents('app.log', $message, FILE_APPEND);
    }
}

$logger = new Logger();
$logger->log("System started\n");

log 方法写入文件,但不返回任何内容。 Void 通常用于具有副作用的方法。 类在所有实例中一致地强制使用 void 返回类型。

返回值时的错误

此示例显示了当 void 函数尝试返回值时会发生什么情况。

void_error.php
<?php

declare(strict_types=1);

function increment(int &$num): void {
    $num++;
    return $num; // This will cause an error
}

$value = 5;
increment($value);

尽管是 void,该函数仍尝试返回递增的值。 在严格模式下,这会导致 TypeError。 该示例演示了 void 强制执行的无返回行为。

带有条件逻辑的 void

此示例显示了一个具有复杂条件路径的 void 函数。

void_conditional.php
<?php

declare(strict_types=1);

function processUser(string $status): void {
    switch ($status) {
        case 'active':
            echo "Processing active user...";
            break;
        case 'inactive':
            echo "Archiving user...";
            break;
        default:
            echo "Unknown status.";
    }
}

processUser('active');

该函数处理不同的状态情况,而不返回值。 通过该函数的所有路径都不得返回任何内容。 Void 确保所有条件分支之间的一致性。

接口定义中的 void

此示例演示了在接口方法声明中使用 void。

void_interface.php
<?php

declare(strict_types=1);

interface Notifier {
    public function send(string $message): void;
}

class EmailNotifier implements Notifier {
    public function send(string $message): void {
        echo "Sending email: $message";
    }
}

$notifier = new EmailNotifier();
$notifier->send("Important update");

接口为 send 方法定义了 void 返回类型。 实现类必须匹配此签名。 接口中的 Void 强制在实现之间保持一致的行为。

用于事件处理程序的 void

此示例显示了在事件处理程序模式中使用 void。

void_event.php
<?php

declare(strict_types=1);

class Button {
    private $clickHandler;

    public function setClickHandler(callable $handler): void {
        $this->clickHandler = $handler;
    }

    public function click(): void {
        if ($this->clickHandler) {
            ($this->clickHandler)();
        }
    }
}

$button = new Button();
$button->setClickHandler(function(): void {
    echo "Button clicked!";
});
$button->click();

点击处理程序是一个 void 回调函数。 处理程序和 click 方法都使用 void,因为它们不返回值。 这对于事件驱动的代码来说很典型,在这种代码中,动作比返回更重要。

最佳实践

来源

PHP 返回类型文档

本教程通过实际示例介绍了 PHP 的 void 返回类型,展示了它在函数、方法、接口和回调中的用法。

作者

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

列出 所有 PHP 教程