简体   繁体   English

PHP Null合并运算符混乱

[英]PHP Null coalescing operator confusion

I'm a bit confused. 我有点困惑。 The PHP documenation says: PHP文档指出:

// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}

But my own example says something very different: 但是我自己的例子却说出了非常不同的东西:

echo "<pre>";
$array['intValue'] = time();
$array['stringValue'] = 'Hello world!';
$array['boolValue'] = false;


$resultInt = isset($array['intValue']) ?? -1;
$resultString = isset($array['stringValue']) ?? 'Another text';
$resultBool = isset($array['boolValue']) ?? true;

var_dump($resultInt);
var_dump($resultString);
var_dump($resultBool);

echo '<br/>';

if(isset($array['intValue'])) $_resultInt = $array['intValue'];
else $_resultInt = -1;

if(isset($array['stringValue'])) $_resultString = $array['stringValue'];
else $_resultString = 'Another text';

if(isset($array['boolValue'])) $_resultBool = $array['boolValue'];
else $_resultBool = true;


var_dump($_resultInt);
var_dump($_resultString);
var_dump($_resultBool);

echo "</pre>";

My output: 我的输出:

bool(true)
bool(true)
bool(true)

int(1534272962)
string(12) "Hello world!"
bool(false)

So, as my example shows, the if-condition does not result in the same as the null coalescing operator does as the documentation says. 因此,如我的示例所示,if条件与文档中所说的空合并运算符的结果不同。 Can somebody explain me, what I did wrong? 有人可以解释我,我做错了什么吗?

Thank you! 谢谢!

You're doing: 你在做:

$resultInt = isset($array['intValue']) ?? -1;
$resultString = isset($array['stringValue']) ?? 'Another text';
$resultBool = isset($array['boolValue']) ?? true;

But the point of ?? 但是重点呢?? is that it does the isset call for you. 是它为您执行了isset调用。 So try this, just put the values without using isset : 因此,请尝试此操作,而无需使用isset即可放置值:

$resultInt = $array['intValue'] ?? -1;
$resultString = $array['stringValue'] ?? 'Another text';
$resultBool = $array['boolValue'] ?? true;

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

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