PHP 7 - 空合并运算符

在PHP 7中,引入了一个新功能 null coalescing operator(??).它用于与isset()函数一起替换三元操作. Null 合并运算符返回其第一个操作数(如果存在且不为NULL);否则它返回第二个操作数.

示例

<?php
   // fetch the value of $_GET['user'] and returns 'not passed'
   // if username is not passed
   $username = $_GET['username'] ?? 'not passed';
   print($username);
   print("<br/>");

   // Equivalent code using ternary operator
   $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
   print($username);
   print("<br/>");
   // Chaining ?? operation
   $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
   print($username);
?>

它产生以下浏览器输出 :

not passed
not passed
not passed