在检查bool值的情况下,php 7中的<=>如何响应?

lil*_*shu 2 php php-7

在途中看着php 7,但<=>让我困惑.

大多数时候我使用条件运算符,它们在布尔情况下使用(<=>几乎是,但不完全,也能够返回-1).(如果X <=> Y).所以我不确定在下列情况下会发生什么......

if ($x <=> $y) {
    // Do all the 1 things
} else {
    // Do all the 2 things
}
Run Code Online (Sandbox Code Playgroud)

如果事先有......我能期待什么?

$x = 0; $y = 1;
Run Code Online (Sandbox Code Playgroud)

要么

$x = "Carrot"; $y = "Carrot Juice";
Run Code Online (Sandbox Code Playgroud)

要么

$x = "Carrot Juice"; $y = "Carrot";
Run Code Online (Sandbox Code Playgroud)

要么

$x = array(carrot, juice); $y = "carrot juice";
Run Code Online (Sandbox Code Playgroud)

关于这一点的确有足够的案例,令我对它的作用感到困惑.

Bar*_*mar 7

太空飞船运营商(以及其他PHP 7新增功能)在这里用简单的语言解释:

https://blog.engineyard.com/2015/what-to-expect-php-7

它在提供给像这样的函数的比较函数中非常有用usort.

// Pre PHP 7
function order_func($a, $b) {
    return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
}

// Post PHP 7
function order_func($a, $b) {
    return $a <=> $b;
}
Run Code Online (Sandbox Code Playgroud)

它不是很有用if,因为if只检查该值是真或假,所以不区分表示排序的不同真值.如果你确实在布尔上下文中使用它,那么当它们相等时true(因为1并且-1很麻烦),false当它们相等时(因为它0是假的),它将被考虑.这类似于尝试使用strcmp()stricmp()在布尔上下文中,这就是你经常看到的原因

if (stricmp($x, $y) == 0)
Run Code Online (Sandbox Code Playgroud)

这里给出了使用带比较运算符的数组的规则(向下滚动到标记为Comparison with Various Types的表).将数组与另一个数组进行比较时,规则为:

具有较少成员的数组较小,如果在操作数2中找不到操作数1的键,则数组是无法比较的,否则 - 按值比较值

将数组与其他类型进行比较时,数组总是更大.所以array('carrot', 'juice') <=> 'carrot juice'1.