簡介
PHP 8
引入了 ?->
(Nullsafe
操作符),用于簡化 null
檢查,減少繁瑣的 if
語句或 isset()
代碼,提高可讀性。
?-> Nullsafe 操作符的作用
在 PHP 7
及以下,訪問對象的屬性或方法時,如果對象是 null
,會導致致命錯誤 (Fatal error
):
$person = null;
echo $person->name; // Fatal error: Uncaught Error: Trying to get property of non-object
解決方案(傳統寫法):
$person = null;
echo isset($person) ? $person->name : null;
PHP 8
解決方案(?->
):
$person = null;
echo $person?->name; // 不會報錯,直接返回 null
?-> 基本用法
訪問對象的屬性
class Person {public string $name = "John";
}$person = new Person();
echo $person?->name; // 輸出 "John"$person = null;
echo $person?->name; // 輸出 null,不會報錯
訪問對象的方法
class User {public function getName() {return "Alice";}
}$user = new User();
echo $user?->getName(); // 輸出 "Alice"$user = null;
echo $user?->getName(); // 輸出 null,不會報錯
訪問嵌套對象
class Address {public string $city = "New York";
}class Person {public ?Address $address = null;
}$person = new Person();
echo $person->address?->city; // 輸出 null,不會報錯$person->address = new Address();
echo $person->address?->city; // 輸出 "New York"
?-> 結合數組
不能用于數組索引([]
),但可以用于 ArrayAccess
對象
$data = null;
echo $data?['key']; // 語法錯誤:不能用于數組
解決方案:使用 ArrayAccess
對象
class Collection implements ArrayAccess {private array $items = ['name' => 'Alice'];public function offsetExists($offset) { return isset($this->items[$offset]); }public function offsetGet($offset) { return $this->items[$offset] ?? null; }public function offsetSet($offset, $value) { $this->items[$offset] = $value; }public function offsetUnset($offset) { unset($this->items[$offset]); }
}$collection = new Collection();
echo $collection?->offsetGet('name'); // 輸出 "Alice"$collection = null;
echo $collection?->offsetGet('name'); // 輸出 null,不會報錯
?-> 結合函數返回值
function getUser() {return null;
}echo getUser()?->name; // 輸出 null,不會報錯
?-> 結合鏈式調用
PHP 8
允許鏈式 ?->
操作,簡化復雜的 null
檢查:
class Department {public ?Person $manager = null;
}$department = new Department();// 傳統寫法
echo isset($department->manager) ? $department->manager->name : null;// PHP 8 `?->`
echo $department?->manager?->name; // 輸出 null,不會報錯
?-> 結合賦值
?->
不能用于賦值,只能用于訪問!
$person = null;// 不能用 `?->` 進行賦值
$person?->name = "John"; // 語法錯誤
解決方案:
if ($person !== null) {$person->name = "John";
}
?-> 不能用于靜態方法
class Test {public static function hello() {return "Hello";}
}echo Test?->hello(); // ? 語法錯誤
靜態方法必須用 ::
訪問,不支持 ?->
解決方案:
echo isset(Test::hello) ? Test::hello() : null;
?-> 和 ?? 的區別
?->
用于對象,??
用于 null
合并
$person = null;// `?->` 適用于對象
echo $person?->name; // 返回 null// `??` 適用于變量為空時提供默認值
echo $person?->name ?? "Default Name"; // 輸出 "Default Name"
-
?->
用于安全訪問對象的屬性或方法。 -
??
用于null
合并,提供默認值。