简体   繁体   English

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

[英]PHP null coalescing operator confusion - how to use in an if statement?

I usually do this in PHP to handle post parameters...我通常在 PHP 中执行此操作来处理后参数...

if (isset($_POST['name'])) {

    echo 'This is the post section';
    echo 'Output Attributes';
    echo $attribute1
    echo $attribute2

} else {

    echo 'The post is empty';

}

In an attempt to simplyfy things I am trying to use the null coalescing operator but I am slightly confused.为了简化事情,我尝试使用 null 合并运算符,但我有点困惑。 uising an exmample I have this..使用一个例子我有这个..

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

But how do I get this to act like an if statement so I can output different sections for example?但是我怎样才能让它像一个if语句一样,所以我可以 output 例如不同的部分?

I think it depends.我认为这取决于。 One way would be:一种方法是:

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

The operator is cool, but it can't do everything.操作员很酷,但它不能做所有事情。 And here it doesn't make it better.在这里它并没有让它变得更好。

This:这个:

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

is equivalent to this:相当于:

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

If you want to do anything more complicated than that, you have to go with your own if/else statement.如果你想做比这更复杂的事情,你必须用你自己的if/else语句来 go 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM