使用带有类私有函数的php中的usort

Ibu*_*Ibu 112 php arrays sorting object

确定使用带有函数的usort并不是那么复杂

这就是我之前在线性代码中所拥有的

function merchantSort($a,$b){
    return ....// stuff;
}

$array = array('..','..','..');
Run Code Online (Sandbox Code Playgroud)

我只是这样做

usort($array,"merchantSort");
Run Code Online (Sandbox Code Playgroud)

现在我们正在升级代码并删除所有全局函数并将它们放在适当的位置.现在所有代码都在一个类中,我无法弄清楚如何使用usort函数使用参数作为对象方法而不是简单函数对数组进行排序

class ClassName {
   ...

   private function merchantSort($a,$b) {
       return ...// the sort
   }

   public function doSomeWork() {
   ...
       $array = $this->someThingThatReturnAnArray();
       usort($array,'$this->merchantSort'); // ??? this is the part i can't figure out
   ...

   }
}
Run Code Online (Sandbox Code Playgroud)

问题是如何在usort()函数中调用对象方法

Dem*_*cht 221

使您的排序功能静态:

private static function merchantSort($a,$b) {
       return ...// the sort
}
Run Code Online (Sandbox Code Playgroud)

并使用数组作为第二个参数:

$array = $this->someThingThatReturnAnArray();
usort($array, array('ClassName','merchantSort'));
Run Code Online (Sandbox Code Playgroud)

  • @MarcoW.,我认为ClassName和merchantSort之间缺少第二个':'.此外,如果函数在同一个类本身内部使用,我用`'self :: merchantSort'`测试它并且它正在工作. (10认同)
  • 男人,这似乎是一种奇怪的方式来做到这一点.哦,PHP,我们如何爱你. (7认同)
  • 如果你使函数静态(你应该),你可以只写`usort($ array,'ClassName:merchantSort')`,不是吗? (4认同)
  • 这很棒!我还想指出sort函数不必作为静态方法*隐式声明*; 因为它仍然可以工作:) (2认同)

dec*_*eze 72

  1. 打开手册页http://www.php.net/usort
  2. 看到的类型$value_compare_funccallable
  3. 单击链接关键字以访问http://php.net/manual/en/language.types.callable.php
  4. 看到语法是 array($this, 'merchantSort')


Jus*_*tin 15

你需要通过$this例如:usort( $myArray, array( $this, 'mySort' ) );

完整示例:

class SimpleClass
{                       
    function getArray( $a ) {       
        usort( $a, array( $this, 'nameSort' ) ); // pass $this for scope
        return $a;
    }                 

    private function nameSort( $a, $b )
    {
        return strcmp( $a, $b );
    }              

}

$a = ['c','a','b']; 
$sc = new SimpleClass();
print_r( $sc->getArray( $a ) );
Run Code Online (Sandbox Code Playgroud)


Jam*_*s K 5

在此示例中,我按数组中名为 AverageVote 的字段进行排序。

您可以在调用中包含该方法,这意味着您不再有类范围问题,就像这样......

        usort($firstArray, function ($a, $b) {
           if ($a['AverageVote'] == $b['AverageVote']) {
               return 0;
           }

           return ($a['AverageVote'] < $b['AverageVote']) ? -1 : 1;
        });
Run Code Online (Sandbox Code Playgroud)


小智 5

在Laravel(5.6)模型类中,我这样称呼它,两个方法都是公共静态的,在windows 64位上使用php 7.2。

public static function usortCalledFrom() 

public static function myFunction()
Run Code Online (Sandbox Code Playgroud)

我确实像这样调用了 usortCalledFrom()

usort($array,"static::myFunction")
Run Code Online (Sandbox Code Playgroud)

这些都不是工作

usort($array,"MyClass::myFunction")
usort($array, array("MyClass","myFunction")
Run Code Online (Sandbox Code Playgroud)