-4

随着新 PHP 版本 PHP 7 的发布,引入了新功能。在这些新功能中,有一个我不熟悉的运算符。Null coalesce operator。_

这个运算符是什么,有哪些好的用例?

4

3 回答 3

4

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

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

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

(不依赖于语言)

用例

你可以写

$rabbits;

$rabbits = count($somearray);

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

您可以使用较短的符号

$rabbits = $rabbits ?? 0;
于 2015-11-12T07:30:33.140 回答
1

According to the PHP Manual:

The null coalesce operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

// 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';
于 2015-11-12T07:53:27.203 回答
0
$username = $_GET['user'] ?? 'nobody'; 

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

?? 是三元速记

于 2015-11-12T07:42:31.053 回答