What is the 'Null coalesce' (??) operator used for?

With the release of a new PHP version, PHP 7, new features are introduced. among these new features is an operator I am not familiar with. The Null coalesce operator .

What is this operator and what are some good use cases?


You can use it to init a variable that might be null

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

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

(not dependent on language)

Use case

You can write

$rabbits;

$rabbits = count($somearray);

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

You can use the shorter notation

$rabbits = $rabbits ?? 0;

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';

$username = $_GET['user'] ?? 'nobody'; 

is same as

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

?? is ternary shorthand

链接地址: http://www.djcxy.com/p/57954.html

上一篇: 空合并运算符的正确关联如何表现?

下一篇: 什么是'空合并'(?)运算符用于?