本文目录导读:

在 PHP 中,可空类型允许变量接受指定类型的值或 null,以下是详细的使用方法:
基本语法
在类型声明前加上 符号:
<?php
// 基本类型可空
function greet(?string $name): string {
return "Hello, " . ($name ?? "Guest");
}
echo greet("John"); // Hello, John
echo greet(null); // Hello, Guest
参数类型的可空
<?php
// 可空参数
function processUser(?User $user): void {
if ($user === null) {
echo "No user provided";
return;
}
echo $user->getName();
}
class User {
public function getName(): string {
return "Alice";
}
}
processUser(new User()); // Alice
processUser(null); // No user provided
返回类型的可空
<?php
// 可空返回类型
function findUser(int $id): ?User {
if ($id <= 0) {
return null;
}
return new User($id);
}
$user = findUser(1); // 返回 User 对象
$user = findUser(-1); // 返回 null
属性类型的可空(PHP 7.4+)
<?php
class Employee {
public ?string $name = null;
public ?int $age = null;
public ?Department $department = null;
}
$emp = new Employee();
$emp->name = "Bob"; // 合法
$emp->age = 30; // 合法
$emp->department = null; // 合法
联合类型中的可空(PHP 8.0+)
<?php
// PHP 8.0+ 支持更灵活的类型声明
function processValue(string|int|null $value): void {
echo $value ?? "null received";
}
processValue("text"); // text
processValue(123); // 123
processValue(null); // null received
常用场景示例
数据库查询
<?php
function fetchUser(int $userId): ?User {
$user = $db->find($userId);
return $user ?: null; // 没找到返回 null
}
$user = fetchUser(123);
if ($user === null) {
echo "User not found";
} else {
echo "User: " . $user->getName();
}
配置处理
<?php
class Config {
public ?string $apiKey = null;
public ?int $timeout = null;
public function getTimeout(): ?int {
return $this->timeout;
}
}
$config = new Config();
$timeout = $config->getTimeout() ?? 30; // 默认值 30
注意事项
参数默认值
<?php
// 正确写法
function test(?string $name = null): void {
echo $name ?? "No name";
}
// 错误写法(会报错)
function errorTest(string $name = null): void {
echo $name;
}
null 安全操作符(PHP 8.0+)
<?php
class User {
public ?Profile $profile = null;
}
$user = new User();
$user->profile?->getName(); // profile 为 null,返回 null,不会报错
完整示例
<?php
class Product {
public ?string $name = null;
public ?float $price = null;
}
class ProductService {
// 返回可空对象
public function findProduct(int $id): ?Product {
// 模拟数据库查询
if ($id === 1) {
return new Product();
}
return null;
}
// 接受可空参数
public function displayProduct(?Product $product): string {
if ($product === null) {
return "Product not found";
}
return "Product: " . ($product->name ?? "Unknown") . " - $" . ($product->price ?? 0);
}
}
$service = new ProductService();
$product = $service->findProduct(1); // Product
echo $service->displayProduct($product);
$notFound = $service->findProduct(99); // null
echo $service->displayProduct($notFound); // Product not found
- 使用
?Type声明可空类型 - 可用于参数、返回值、属性
- PHP 8.0+ 支持联合类型中的
null - 配合 (null 合并运算符)使用更高效
- 可空类型让代码更清晰地表达“可能为空”的业务逻辑