【发布时间】:2018-09-28 13:06:57
【问题描述】:
我个人发现自己使用它很多次只是为了防止在尝试访问数组时出现“未定义索引”异常。
此外,我发现自己使用它来检查数组是否包含该键。您会在下面找到一个示例:
function getValue($key)
{
return $this->array[$key] ?? null;
}
// ---
if (!$object->get('key'))
// Do something when the array doesn't contain that key or the value is empty.
什么时候可以使用空合并运算符,什么时候不可以?可以这样使用它还是建议以其他方式做这样的事情?
【问题讨论】:
-
您的用例无法区分键不存在和其值为 falsey...
标签: php null-coalescing-operator