什么是PHP中的<=>('太空飞船'运算符)?

Dee*_*tia 184 php operators spaceship-operator php-7

PHP 7将于今年11月推出,它将引入Spaceship(<=>)运营商.它是什么以及它是如何工作的?

关于PHP运算符的一般参考问题,这个问题已经有了答案.

Gre*_*OBO 255

<=>运营商将提供综合比较,它将:

Return 0 if values on either side are equal
Return 1 if value on the left is greater
Return -1 if the value on the right is greater
Run Code Online (Sandbox Code Playgroud)

组合比较运算符使用的规则与PHP当前使用的比较运算符相同.<,<=,==,>=>.那些来自Perl或Ruby编程背景的人可能已经熟悉为PHP7提出的这个新运算符.

   //Comparing Integers

    echo 1 <=> 1; //output  0
    echo 3 <=> 4; //output -1
    echo 4 <=> 3; //output  1

    //String Comparison

    echo "x" <=> "x"; //output  0
    echo "x" <=> "y"; //output -1
    echo "y" <=> "x"; //output  1
Run Code Online (Sandbox Code Playgroud)

  • 但是字符串是如何比较的?它是在查看字符,字符串中的字符数等等吗? (11认同)
  • @AltafHussain 看到这个答案:(http://stackoverflow.com/a/17371819/4337069) (2认同)

Mar*_*ery 57

根据引入运算符的RFC,$a <=> $b评估为:

  • 0如果 $a == $b
  • -1如果 $a < $b
  • 1如果 $a > $b

这似乎是在每一个我试过方案实践的情况下,虽然严格的官方文档只提供稍弱保证$a <=> $b将返回

整数小于,等于或大于零的时候$a是分别小于,等于或大于$b

无论如何,你为什么要这样的运营商?同样,RFC解决了这个-这几乎是完全以使其更方便地编写比较功能usort(以及类似的uasortuksort).

usort将数组排序为其第一个参数,并将用户定义的比较函数作为其第二个参数.它使用该比较函数来确定数组中的哪一对元素更大.比较函数需要返回:

如果第一个参数被认为分别小于,等于或大于第二个参数,则小于,等于或大于零的整数.

宇宙飞船运营商简洁明了:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});
Run Code Online (Sandbox Code Playgroud)

使用太空飞船运营商编写的比较函数的更多示例可以在RFC 的实用性部分找到.

  • 对我来说,“什么是”问题不仅是“它做什么”,而且是“它是做什么的,在哪里可以看到”,因此我认为这是正确而完整的答案:) (7认同)