PHP Null合并运算符混乱 [英] PHP Null coalescing operator confusion
本文介绍了PHP Null合并运算符混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有点困惑. 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>";
我的输出:
bool(true)
bool(true)
bool(true)
int(1534272962)
string(12) "Hello world!"
bool(false)
因此,如我的示例所示,if条件与文档中所说的空合并运算符的结果不同.有人可以解释我,我做错了什么吗?
So, as my example shows, the if-condition does not result in the same as the null coalescing operator does as the documentation says. Can somebody explain me, what I did wrong?
谢谢!
推荐答案
您正在做的事情:
$resultInt = isset($array['intValue']) ?? -1;
$resultString = isset($array['stringValue']) ?? 'Another text';
$resultBool = isset($array['boolValue']) ?? true;
但是??
的要点是它为您执行了isset
调用.因此,请尝试使用此方法,而无需使用isset
:
But the point of ??
is that it does the isset
call for you. So try this, just put the values without using isset
:
$resultInt = $array['intValue'] ?? -1;
$resultString = $array['stringValue'] ?? 'Another text';
$resultBool = $array['boolValue'] ?? true;
这篇关于PHP Null合并运算符混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文