PHP null合并运算符混淆-如何在if语句中使用

  • 本文关键字:if 语句 合并 null 运算符 PHP php
  • 更新时间 :
  • 英文 :


我通常在PHP中这样做是为了处理post参数。。。

if (isset($_POST['name'])) {
echo 'This is the post section';
echo 'Output Attributes';
echo $attribute1
echo $attribute2
} else {
echo 'The post is empty';
}

为了简化事情,我尝试使用null合并运算符,但我有点困惑。举个例子,我有这个。。

$name = $_POST['name'] ?? 'The post is empty';

但是,我如何让它表现得像if语句,以便输出不同的部分呢?

这:

$name = $_POST['name'] ?? 'The post is empty';

相当于:

if(isset($_POST['name'])){
$name = $_POST['name'];
}else{
$name = 'The post is empty';
}

如果你想做比这更复杂的事情,你必须使用你自己的if/else语句。

我认为这取决于情况。一种方法是:

<?php if ( $_POST['name'] ?? false ) {  } else {} ?>

操作员很酷,但它不能做所有事情。在这里,它并没有让它变得更好。

最新更新