php 8 中,对可能为 null 的对象用 ?-> 读取属性。某一层为空时,后续链式访问会停止并得到 null,再用 ?? 提供默认值。
给每个可能为空的对象使用 ?->
把下面代码保存为 profile.php。用户和用户资料都可能为空,所以两个访问点都用空安全运算符。
<?php
class Profile
{
public function __construct(public string $city) {}
}
class User
{
public function __construct(public ?Profile $profile) {}
}
function cityLabel(?User $user): string
{
return $user?->profile?->city ?? '未填写';
}
如果只在 user 后用 ?->,但 profile 也可能为空,就仍需处理第二层。
核对有资料、无资料和无用户三种情况
把下面几行追加到文件末尾,执行 php profile.php。
立即学习“PHP免费学习笔记(深入)”;
echo cityLabel(new User(new Profile('杭州'))), PHP_EOL;
echo cityLabel(new User(null)), PHP_EOL;
echo cityLabel(null), PHP_EOL;
结果依次是杭州、未填写、未填写。
需要写入时先判断对象存在
空安全运算符只能用于读取或调用,不能作为赋值目标。
$user = new User(new Profile('杭州'));
$profile = $user?->profile;
if ($profile !== null) {
$profile->city = '苏州';
}
echo cityLabel($user), PHP_EOL;预期输出苏州。对于数组键,应使用数组访问和适用的缺省处理。



















