Skip to content

return 语句

return 语句用于从函数中返回值,或者终止脚本文件(当在全局作用域中使用时)。它是函数与外部代码通信的主要方式。在 include 的文件中,return 还可以返回值给包含它的脚本。

前置知识

基础概念

return 的主要用途:

  1. 从函数返回值:将计算结果传回调用者。
  2. 终止函数执行:在函数的任意位置提前结束执行。
  3. 从包含文件返回值:在 include/require 的文件中使用 return 可以向包含方返回一个值。
  4. 终止脚本执行:在全局作用域中使用 return 可以终止当前脚本。

语法结构

从函数返回值

php
<?php
declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

$result = add(3, 5);
echo "3 + 5 = {$result}\n";
// 输出:3 + 5 = 8

提前返回(Early Return)

php
<?php
declare(strict_types=1);

function getDiscount(int $age, string $membership): float
{
    // 使用 Early Return 减少嵌套
    if ($age < 18) {
        return 0.5;  // 未成年半价
    }

    if ($age >= 65) {
        return 0.7;  // 老年人七折
    }

    return match ($membership) {
        'gold'   => 0.8,
        'silver' => 0.9,
        default  => 1.0,
    };
}

echo "未成年:5折\n";
echo "老年人:7折\n";
echo "金牌会员:8折\n";

无返回值的函数

php
<?php
declare(strict_types=1);

function logMessage(string $message, string $level = 'info'): void
{
    $timestamp = date('Y-m-d H:i:s');
    $formatted = "[{$timestamp}] [{$level}] {$message}\n";

    // void 函数也可以使用 return 提前退出
    if ($message === '') {
        return;
    }

    echo $formatted;
}

logMessage('服务启动成功');
logMessage('连接超时', 'error');
logMessage('');

返回多种类型

php
<?php
declare(strict_types=1);

function findUserById(int $id): array|null
{
    $users = [
        1 => ['name' => '张三', 'email' => 'zhang@example.com'],
        2 => ['name' => '李四', 'email' => 'li@example.com'],
    ];

    return $users[$id] ?? null;
}

$user = findUserById(1);

if ($user !== null) {
    echo "找到用户:{$user['name']}\n";
} else {
    echo "用户不存在\n";
}

详细说明

return vs exit

特性returnexit/die
作用域函数内部终止函数,全局作用域终止当前文件终止整个脚本进程
在 include 中返回值给包含方终止整个脚本
清理资源执行析构函数和 shutdown 函数执行 shutdown 函数
用途函数返回、文件返回值致命错误、脚本终止
可测试性适合单元测试难以测试
php
<?php
declare(strict_types=1);

// return:仅终止当前函数
function process(string $data): string
{
    if ($data === '') {
        return '空数据'; // 函数正常返回
    }

    return strtoupper($data);
}

echo process('hello') . "\n"; // HELLO
echo process('') . "\n";     // 空数据

在 include 文件中使用 return

被包含的文件可以使用 return 向包含方返回一个值。这是一种常见的配置文件加载模式。

php
<?php
// file: config.php
declare(strict_types=1);

return [
    'database' => [
        'host'     => 'localhost',
        'port'     => 3306,
        'name'     => 'myapp',
        'username' => 'root',
        'password' => 'secret',
    ],
    'app' => [
        'debug'  => true,
        'locale' => 'zh-CN',
    ],
];
php
<?php
// file: index.php
declare(strict_types=1);

// 包含 config.php 并获取返回值
$config = include __DIR__ . '/config.php';

echo "数据库主机:{$config['database']['host']}\n";
echo "应用语言:{$config['app']['locale']}\n";
echo "调试模式:" . ($config['app']['debug'] ? '开启' : '关闭') . "\n";

在全局作用域中使用 return

在全局作用域(非函数内部)中使用 return 会终止当前脚本的执行。如果当前脚本是被 includerequire 的,则只终止该包含文件的执行。

php
<?php
// file: included_file.php
declare(strict_types=1);

echo "开始执行包含文件\n";

$shouldStop = true;

if ($shouldStop) {
    echo "包含文件提前终止\n";
    return; // 只终止这个文件,不影响主脚本
}

echo "这行不会执行\n";
php
<?php
// file: main.php
declare(strict_types=1);

echo "主脚本开始\n";

include __DIR__ . '/included_file.php';

echo "主脚本继续执行\n";
// 输出:
// 主脚本开始
// 开始执行包含文件
// 包含文件提前终止
// 主脚本继续执行

返回引用

函数可以返回引用,允许调用者通过引用修改函数内部的变量。这种用法比较少见,通常用于特定设计模式。

php
<?php
declare(strict_types=1);

class Config
{
    private array $values = [];

    public function &getReference(string $key): mixed
    {
        if (!isset($this->values[$key])) {
            $this->values[$key] = null;
        }
        return $this->values[$key];
    }
}

$config = new Config();
$ref = &$config->getReference('timeout');
$ref = 30; // 直接修改内部值

echo "timeout: " . $config->getReference('timeout') . "\n";

实战示例

分层验证

php
<?php
declare(strict_types=1);

function validateAndProcess(array $input): array
{
    // 第一层:必填字段验证
    if (empty($input['username'])) {
        return ['success' => false, 'error' => '用户名不能为空'];
    }

    if (empty($input['email'])) {
        return ['success' => false, 'error' => '邮箱不能为空'];
    }

    // 第二层:格式验证
    if (!filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
        return ['success' => false, 'error' => '邮箱格式不正确'];
    }

    if (strlen($input['username']) < 3) {
        return ['success' => false, 'error' => '用户名至少 3 个字符'];
    }

    // 第三层:业务处理
    return [
        'success' => true,
        'data'    => [
            'username' => trim($input['username']),
            'email'    => strtolower($input['email']),
        ],
    ];
}

$result1 = validateAndProcess(['username' => '', 'email' => 'test@test.com']);
echo "结果1:" . ($result1['success'] ? '成功' : $result1['error']) . "\n";

$result2 = validateAndProcess(['username' => 'john', 'email' => 'invalid']);
echo "结果2:" . ($result2['success'] ? '成功' : $result2['error']) . "\n";

$result3 = validateAndProcess(['username' => 'john', 'email' => 'john@test.com']);
echo "结果3:" . ($result3['success'] ? '成功' : $result3['error']) . "\n";

配置加载器

php
<?php
declare(strict_types=1);

function loadConfig(string $env): array
{
    $filePath = __DIR__ . "/config/{$env}.php";

    if (!file_exists($filePath)) {
        return ['error' => "配置文件不存在:{$filePath}"];
    }

    $config = include $filePath;

    if (!is_array($config)) {
        return ['error' => '配置文件格式不正确'];
    }

    return $config;
}

// 配置文件需要 return 一个数组
function createDefaultConfig(): array
{
    $tempDir = sys_get_temp_dir();
    $configPath = $tempDir . '/dev_config.php';

    file_put_contents($configPath, '<?php return ["debug" => true, "cache" => false];');

    $config = loadConfig($configPath);
    print_r($config);

    unlink($configPath);
}

createDefaultConfig();

注意事项

  1. void 函数中的 return:标记为 void 返回类型的函数可以使用 return;(无值)提前退出,但不能返回值。

  2. return 后的代码不执行return 之后的任何代码都不会被执行。

  3. 在 try/catch 中return 会在执行 finally 块之后才真正返回。

  4. 全局 return 与 exit:在全局作用域中,return 只终止当前文件(如果是被 include 的),而 exit 会终止整个脚本。

最佳实践

  1. 使用 Early Return:将失败条件放在函数前面,尽早返回,减少代码嵌套层级。

  2. 保持返回类型一致:一个函数应该只返回一种逻辑类型。如果可能返回多种类型,使用联合类型并明确文档说明。

  3. 配置文件使用 return:这是 PHP 配置文件的标准模式,被广泛采用(如 Laravel、Symfony 等框架)。

  4. 避免在构造函数中使用 return:构造函数不应返回值(PHP 也不允许)。

  5. 使用联合类型和 null 安全(PHP 8.0+):利用类型系统让调用者清楚函数可能返回 null 的情况。

下一节

return 终止函数,而 exit/die 终止整个脚本。接下来学习 exit/die

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接