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

早过忘川 提交于 2019-12-04 07:13:20

问题


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?


回答1:


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;



回答2:


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



回答3:


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

is same as

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

?? is ternary shorthand



来源:https://stackoverflow.com/questions/33666256/what-is-the-null-coalesce-operator-used-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!