【问题标题】:What is the 'Null coalesce' (??) operator used for? [closed]'Null coalesce' (??) 运算符用于什么? [关闭]
【发布时间】:2015-11-12 07:28:17
【问题描述】:
随着新 PHP 版本 PHP 7 的发布,引入了新功能。在这些新功能中,有一个我不熟悉的运算符。 Null coalesce operator。
这个运算符是什么,有哪些好的用例?
【问题讨论】:
-
来自manual:“已添加空合并运算符 (??) 作为语法糖,用于需要与 isset() 结合使用三元的常见情况。它如果存在且不为 NULL,则返回其第一个操作数;否则返回其第二个操作数。"
标签:
php
coding-style
operators
php-7
【解决方案2】:
根据 PHP 手册:
已添加空合并运算符 (??) 作为语法糖,用于需要将三元组与 isset() 结合使用的常见情况。如果存在且不为 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';
【解决方案3】:
$username = $_GET['user'] ?? 'nobody';
与
相同
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
??是三元速记