【问题标题】:Is the null-coalescing operator a good thing?空合并运算符是一件好事吗?
【发布时间】: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


【解决方案1】:

PHP Manual for the NULL COALESCING OPERATOR 列出了一个类似的例子:

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

所以我认为以这种方式使用它是安全的。

什么时候可以使用空合并运算符,什么时候不可以?

当你不需要区分NULL值和UNDEFINED值时使用它是可以的,并且你可以将它们视为相同,就好像它们都是NULL一样。

【讨论】:

    猜你喜欢
    • 2012-11-07
    • 2012-09-19
    • 1970-01-01
    • 2010-10-20
    • 2020-06-22
    • 1970-01-01
    • 2011-06-19
    • 2013-09-13
    • 2012-05-20
    相关资源
    最近更新 更多