PHP ussort comparator函数需要访问类成员变量-如何调用它


PHP usort comparator function needs access to class member variables - how to call it

我试图在PHP中使用usort()函数。我不确定如何调用比较函数。下面是我的代码。我试过$this->comparator,但没有帮助。如果comparator是一个不需要访问类成员变量的函数,这将是很容易的。

class A { 
   $p1    // non-associative array 
   $p2    // non-associative array
   public function comparator($a, $b)
   {
       // the usual comparison stuff
       if ($this->p1[$a] == $this->p2[$b])
            return 0; 
       else ($this->p1[$a] < $this->p2[$b])
            return 1; 
       else
            return -1;
   }
   public function sorting()
   {
      // after some code
      $some_array = array(..); 
      usort($some_array, "comparator")    // <--- ERROR here: does not recognize comparator
   }
}

您需要以可调用的方式指定排序函数:

usort($some_array, array($this, "comparator"));

尽管在PHP 5.4之前不存在callable类型,但是引用方法的工作方式是一样的