【发布时间】:2023-03-07 20:30:01
【问题描述】:
我有点困惑。 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 条件的结果与文档所述的 null 合并运算符的结果不同。谁能解释一下,我做错了什么?
谢谢!
【问题讨论】:
标签: php output operator-keyword