我有点困惑。 PHP documenation说:
// 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';
}
但是我自己的示例说的却非常不同:
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条件与文档中所说的空合并运算符的结果不同。有人可以解释一下我做错了什么吗?
谢谢!
答案 0 :(得分:4)
您正在做
$resultInt = isset($array['intValue']) ?? -1;
$resultString = isset($array['stringValue']) ?? 'Another text';
$resultBool = isset($array['boolValue']) ?? true;
但是??
的要点是它为您执行了isset
的呼叫。因此,请尝试此操作,而无需使用isset
:
$resultInt = $array['intValue'] ?? -1;
$resultString = $array['stringValue'] ?? 'Another text';
$resultBool = $array['boolValue'] ?? true;