'Null coalesce' (??) 运算符的用途是什么?



随着PHP新版本PHP7的发布,引入了新功能。在这些新功能中,有一个我不熟悉的操作员。Null coalesce operator

这个操作符是什么?有哪些好的用例?

您可以使用它初始化一个可能为空的变量

??运算符称为空合并运算符。它返回左侧操作数(如果操作数不为空);否则返回右手操作数。

来源:https://msdn.microsoft.com/nl-nl/library/ms173224.aspx

(不依赖于语言)

用例

你可以写

$rabbits;
$rabbits = count($somearray);
if ($rabbits == null) {
    $rabbits = 0;
}

您可以使用较短的表示法

$rabbits = $rabbits ?? 0;

根据PHP手册:

对于需要将三元运算符与isset()结合使用的常见情况,添加了null联合运算符(??)作为语法糖。如果它存在并且不为NULL,则返回其第一个操作数;否则返回第二个操作数。

// 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';
// Coalesces can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
$username = $_GET['user'] ?? 'nobody'; 

与相同

$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

是三元简写

最新更新