[英]Does php spaceship ever return something other than -1, 0, or 1?
According to this , the spaceship operator (<=>) returns "an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y".据此,宇宙飞船运算符 (<=>) 返回“一个小于、等于或大于零的 integer,具体取决于 $x 是小于、等于还是大于 $y”。
Trying it out , it seems to only return -1, 0, or 1. 试一试,似乎只返回-1、0或1。
Is that always the case?总是这样吗?
From PHP's New feature's page :从PHP 的新功能页面:
Spaceship operator
宇宙飞船操作员
The spaceship operator is used for comparing two expressions.
spaceship 运算符用于比较两个表达式。
It returns-1
,0
or1
when$a
is respectively less than, equal to, or greater than$b
.当
$a
分别小于、等于或大于$b
1
,它返回-1
或0
。
Comparisons are performed according to PHP's usual type comparison rules.比较是根据 PHP 常用的类型比较规则进行的。
So, only -1
, 0
or 1
can be returned from <=>
因此,只有
-1
、 0
或1
可以从<=>
返回
The current implementation always returns those values for normal inputs. 当前的实现总是为正常输入返回这些值。 When it compares two numbers, it normalises the result using this macro:
当它比较两个数字时,它使用这个宏来规范化结果:
#define ZEND_NORMALIZE_BOOL(n) \
((n) ? (((n)<0) ? -1 : 1) : 0)
(It does have provision for objects provided by extensions to have their own implementation, though, so those could return a different value.) (不过,它确实为扩展提供的对象提供了自己的实现,因此它们可以返回不同的值。)
However,the official documentation only guarantees "an int less than, equal to, or greater than zero".但是,官方文档只保证“一个 int 小于、等于或大于零”。 Its intended usage is in functions such as usort which look for those values.
它的预期用途是在诸如寻找这些值的函数中。
Since this is a common convention, if you're writing your own code, it's probably better to stick to that than explicitly check for -1 and 1.由于这是一个通用约定,因此如果您正在编写自己的代码,那么坚持下去可能比明确检查 -1 和 1 更好。
That's less likely to cause surprises down the road if the implementation changes, or you need to interact with a different source of comparisons.如果实施发生变化,或者您需要与不同的比较来源进行交互,这不太可能在未来引起意外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.