首页 > 解决方案 > 在回声中使用三元运算符?

问题描述

我怎么可以这样使用回声:

<?php echo false ? 'yes' : 'no'; ?> //no

但是不能这样使用

<?php echo false ?? 'yes'; ?> //nothing output

标签: php

解决方案


这 ??PHP 中的运算符是 Null 合并运算符:

expr1 ?? expr2;

expr1 is returned when expr1 exists and is NOT null; otherwise it returns expr2.

由于在这种情况下 expr1 为假但已设置,因此此表达式返回布尔值假。

比较:

echo false ?? 'It is FALSE'; // won't be displayed
echo null ?? 'it is NULL'; // It will work

当传递布尔值 false 时,Echo 不输出。


推荐阅读