PHP 中三元运算符和空值合并运算符的区别


三元运算符

三元运算符用于将 if else 语句替换为一个语句。

语法

(condition) ? expression1 : expression2;

等价表达式

if(condition) {
   return expression1;
}
else {
   return expression2;
}

如果条件为真,则返回 expression1 的结果,否则返回 expression2 的结果。condition 或 expression 中不允许使用 void。

空值合并运算符

空值合并运算符用于在变量为 null 情况下提供非 null 值。

语法

(variable) ?? expression;

等价表达式

if(isset(variable)) {
   return variable;
}
else {
   return expression;
}

如果变量为 null,则返回表达式的结果。

示例

<!DOCTYPE html>
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
   <?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/>");
   ?>
</body>
</html>

输出

not passed
not passed

更新于: 2020 年 1 月 6 日

430 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.