如何在 PHP 中使用 "Nullsafe operator"
How can I use "Nullsafe operator" in PHP
有没有办法在 php 中使用 Nullsafe operator
条件?
PHP 7
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
PHP 8
$country = $session?->user?->getAddress()?->country;
您现在可以使用带有新的空安全运算符的调用链,而不是空检查条件。当链中一个元素的评估失败时,整个链的执行中止并且整个链评估为空。
Nullsafe 运算符允许您链接调用,避免检查链的每个部分是否不为空(空变量的方法或属性)。
PHP 8.0
$city = $user?->getAddress()?->city
之前 PHP 8.0
$city = null;
if($user !== null) {
$address = $user->getAddress();
if($address !== null) {
$city = $address->city;
}
}
使用 null coalescing operator
(不适用于方法):
$city = null;
if($user !== null) {
$city = $user->getAddress()->city ?? null;
}
Nullsafe operator
抑制错误:
Warning: Attempt to read property "city" on null in Fatal error:
Uncaught Error: Call to a member function getAddress() on null
但是它不适用于数组键:
$user['admin']?->getAddress()?->city //Warning: Trying to access array offset on value of type null
$user = [];
$user['admin']?->getAddress()?->city //Warning: Undefined array key "admin"
有没有办法在 php 中使用 Nullsafe operator
条件?
PHP 7
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
PHP 8
$country = $session?->user?->getAddress()?->country;
您现在可以使用带有新的空安全运算符的调用链,而不是空检查条件。当链中一个元素的评估失败时,整个链的执行中止并且整个链评估为空。
Nullsafe 运算符允许您链接调用,避免检查链的每个部分是否不为空(空变量的方法或属性)。
PHP 8.0
$city = $user?->getAddress()?->city
之前 PHP 8.0
$city = null;
if($user !== null) {
$address = $user->getAddress();
if($address !== null) {
$city = $address->city;
}
}
使用 null coalescing operator
(不适用于方法):
$city = null;
if($user !== null) {
$city = $user->getAddress()->city ?? null;
}
Nullsafe operator
抑制错误:
Warning: Attempt to read property "city" on null in Fatal error:
Uncaught Error: Call to a member function getAddress() on null
但是它不适用于数组键:
$user['admin']?->getAddress()?->city //Warning: Trying to access array offset on value of type null
$user = [];
$user['admin']?->getAddress()?->city //Warning: Undefined array key "admin"