函数返回值 #
一、基本返回值 #
1.1 return语句 #
php
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
$result = add(1, 2);
echo $result;
1.2 提前返回 #
php
<?php
function divide(float $a, float $b): ?float
{
if ($b === 0.0) {
return null;
}
return $a / $b;
}
echo divide(10, 2);
echo divide(10, 0);
1.3 多个return路径 #
php
<?php
function getGrade(int $score): string
{
if ($score >= 90) return "A";
if ($score >= 80) return "B";
if ($score >= 70) return "C";
if ($score >= 60) return "D";
return "F";
}
echo getGrade(85);
二、返回类型声明 #
2.1 基本类型 #
php
<?php
function getInt(): int
{
return 42;
}
function getFloat(): float
{
return 3.14;
}
function getString(): string
{
return "Hello";
}
function getBool(): bool
{
return true;
}
function getArray(): array
{
return [1, 2, 3];
}
2.2 对象类型 #
php
<?php
class User
{
public function __construct(
public string $name
) {}
}
function createUser(string $name): User
{
return new User($name);
}
$user = createUser("John");
echo $user->name;
2.3 接口类型 #
php
<?php
interface LoggerInterface
{
public function log(string $message): void;
}
class FileLogger implements LoggerInterface
{
public function log(string $message): void
{
file_put_contents('app.log', $message . "\n", FILE_APPEND);
}
}
function createLogger(): LoggerInterface
{
return new FileLogger();
}
2.4 可空类型 #
php
<?php
function findUser(int $id): ?User
{
if ($id <= 0) {
return null;
}
return new User("User#$id");
}
$user = findUser(1);
if ($user !== null) {
echo $user->name;
}
2.5 void返回类型 #
php
<?php
function logMessage(string $message): void
{
echo "[" . date('Y-m-d H:i:s') . "] $message\n";
}
logMessage("Application started");
2.6 never返回类型(PHP 8.1+) #
php
<?php
function redirect(string $url): never
{
header("Location: $url");
exit;
}
function throwError(string $message): never
{
throw new Exception($message);
}
三、联合类型(PHP 8.0+) #
3.1 基本用法 #
php
<?php
function process(int|float $number): string
{
return "Number: $number";
}
echo process(42);
echo process(3.14);
3.2 多类型联合 #
php
<?php
function format(string|int|float $value): string
{
return (string) $value;
}
echo format("hello");
echo format(42);
echo format(3.14);
3.3 可空联合类型 #
php
<?php
function getName(): string|null
{
return $this->name;
}
function getName(): ?string
{
return $this->name;
}
四、多返回值 #
4.1 返回数组 #
php
<?php
function getMinMax(array $numbers): array
{
return [
'min' => min($numbers),
'max' => max($numbers),
'avg' => array_sum($numbers) / count($numbers)
];
}
$result = getMinMax([1, 2, 3, 4, 5]);
echo "Min: {$result['min']}, Max: {$result['max']}, Avg: {$result['avg']}";
4.2 解构返回值 #
php
<?php
function getCoordinates(): array
{
return [10, 20];
}
[$x, $y] = getCoordinates();
echo "X: $x, Y: $y";
4.3 命名返回值 #
php
<?php
function parseUrl(string $url): array
{
return [
'scheme' => parse_url($url, PHP_URL_SCHEME),
'host' => parse_url($url, PHP_URL_HOST),
'path' => parse_url($url, PHP_URL_PATH),
];
}
['host' => $host, 'path' => $path] = parseUrl('https://example.com/page');
echo "Host: $host, Path: $path";
4.4 使用对象 #
php
<?php
class Result
{
public function __construct(
public bool $success,
public mixed $data = null,
public ?string $error = null
) {}
}
function fetchData(int $id): Result
{
if ($id <= 0) {
return new Result(false, null, "Invalid ID");
}
return new Result(true, ['id' => $id, 'name' => "Item $id"]);
}
$result = fetchData(1);
if ($result->success) {
print_r($result->data);
}
五、引用返回 #
5.1 基本用法 #
php
<?php
class Counter
{
private int $count = 0;
public function &getCount(): int
{
return $this->count;
}
}
$counter = new Counter();
$count = &$counter->getCount();
$count = 10;
5.2 数组元素引用 #
php
<?php
class Collection
{
private array $items = [];
public function &getItem(int $index): mixed
{
return $this->items[$index];
}
public function setItem(int $index, mixed $value): void
{
$this->items[$index] = $value;
}
}
$collection = new Collection();
$collection->setItem(0, 'original');
$item = &$collection->getItem(0);
$item = 'modified';
5.3 注意事项 #
php
<?php
function &getReference(): int
{
static $value = 0;
return $value;
}
$ref = &getReference();
$ref = 10;
echo getReference();
六、返回值验证 #
6.1 类型检查 #
php
<?php
declare(strict_types=1);
function add(int $a, int $b): int
{
return $a + $b;
}
echo add(1, 2);
echo add(1.5, 2.5);
6.2 返回值验证 #
php
<?php
function createEmail(string $address): ?Email
{
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
return null;
}
return new Email($address);
}
$email = createEmail('user@example.com');
if ($email === null) {
throw new InvalidArgumentException("Invalid email");
}
七、实际应用 #
7.1 工厂方法 #
php
<?php
interface LoggerInterface {}
class FileLogger implements LoggerInterface {}
class DatabaseLogger implements LoggerInterface {}
function createLogger(string $type): LoggerInterface
{
return match($type) {
'file' => new FileLogger(),
'database' => new DatabaseLogger(),
default => throw new InvalidArgumentException("Unknown logger type: $type")
};
}
7.2 链式调用 #
php
<?php
class QueryBuilder
{
private array $select = [];
private string $table = '';
private array $where = [];
public function select(array $columns): self
{
$this->select = $columns;
return $this;
}
public function from(string $table): self
{
$this->table = $table;
return $this;
}
public function where(string $condition): self
{
$this->where[] = $condition;
return $this;
}
public function build(): string
{
$sql = "SELECT " . implode(', ', $this->select);
$sql .= " FROM " . $this->table;
if (!empty($this->where)) {
$sql .= " WHERE " . implode(' AND ', $this->where);
}
return $sql;
}
}
$query = (new QueryBuilder())
->select(['id', 'name'])
->from('users')
->where('active = 1')
->build();
7.3 错误处理 #
php
<?php
class Result
{
private function __construct(
private bool $success,
private mixed $value,
private ?string $error
) {}
public static function ok(mixed $value): self
{
return new self(true, $value, null);
}
public static function error(string $error): self
{
return new self(false, null, $error);
}
public function isSuccess(): bool
{
return $this->success;
}
public function getValue(): mixed
{
return $this->value;
}
public function getError(): ?string
{
return $this->error;
}
}
function divide(float $a, float $b): Result
{
if ($b === 0.0) {
return Result::error("Division by zero");
}
return Result::ok($a / $b);
}
$result = divide(10, 2);
if ($result->isSuccess()) {
echo $result->getValue();
} else {
echo $result->getError();
}
八、最佳实践 #
8.1 明确返回类型 #
php
<?php
function findUser(int $id): ?User
{
}
8.2 使用void表示无返回值 #
php
<?php
function log(string $message): void
{
file_put_contents('app.log', $message . "\n", FILE_APPEND);
}
8.3 避免混合返回类型 #
php
<?php
function process(array $data): array|false
{
if (empty($data)) {
return false;
}
return $data;
}
function process(array $data): ?array
{
if (empty($data)) {
return null;
}
return $data;
}
8.4 使用Result对象 #
php
<?php
function fetchData(int $id): Result
{
if ($id <= 0) {
return Result::error("Invalid ID");
}
return Result::ok($this->repository->find($id));
}
九、总结 #
本章学习了:
- 基本返回值
- 返回类型声明
- 联合类型
- 多返回值
- 引用返回
- 最佳实践
下一章将学习变量作用域。
最后更新:2026-03-26