【问题标题】:PHP Null coalescing operator confusionPHP Null 合并运算符混淆
【发布时间】: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


    【解决方案1】:

    你在做:

    $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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2023-03-23
      • 1970-01-01
      • 2018-04-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多