PHP7 Null合併運算符

在PHP7,一個新的功能,空合併運算符(??)已被引入。它被用來代替三元運算並與 isset()函數功能結合一起使用。如果它存在並且它不是空的,空合併運算符返回它的第一個運算元;否則返回第二個運算元。

示例

<?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

上一篇: PHP7返回類型聲明 下一篇: PHP7飛船操作符