编程爱好者之家

PHP7 Null合并运算符

2018-07-31 11:38:01 224

在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


同类文章