三元运营商(猫王运营商)?:

时间:2018-04-16 10:24:29

标签: php

我只是想知道为什么这段代码会返回1

$complete = 'complete';
$completed = ($complete == 'complete') ?: 'Not Complete';

如果我试试这个

$complete = 'complete';
$completed = ($complete == 'complete') ? $complete : 'Not Complete';

和这一个

$complete = 'complete';
if ($complete == 'complete') {
    $completed = $complete;
} else {
    $completed = 'Not Complete';
}

他们都返回'complete'

基于此?: operator (the 'Elvis operator') in PHP

他们都不应该返回相同的值吗?

2 个答案:

答案 0 :(得分:3)

这是因为您在第一个示例中进行了布尔检查:

$complete == 'complete' // returns 'true'

操作员告诉如果语句为真,则返回语句的值,否则返回'not Complete'。它确实如此。 true表示为1

您的示例解释:

// sets '$completed' to '($complete == 'complete')' what is 'true'
$completed = ($complete == 'complete') ?: 'Not Complete';

// sets '$completed' to '$completed', what is 'NULL', because '$completed' seems to be undefined before
$completed = ($complete == 'complete') ? $completed : 'Not Complete';

// sets '$completed' to the value of '$complete', because the statement is 'true'
if ($complete == 'complete') {
    $completed = $complete;
} else {
    $completed = 'Not Complete';
}

答案 1 :(得分:0)

您可以这样使用Elvis Operator:

$completed = $complete ?: 'Not Complete';

在您的代码中,您有一个类似这种情况的声明:

$completed = true ?: 'Not Complete';

因此它返回true。