问题
I'm a bit confused. The PHP documenation says:
// 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. Can somebody explain me, what I did wrong?
Thank you!
回答1:
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. So try this, just put the values without using isset
:
$resultInt = $array['intValue'] ?? -1;
$resultString = $array['stringValue'] ?? 'Another text';
$resultBool = $array['boolValue'] ?? true;
来源:https://stackoverflow.com/questions/51848077/php-null-coalescing-operator-confusion