2013-06-15 2 views
2

PHP에서 usort() 함수를 사용하려고합니다. 비교 함수를 호출하는 방법을 잘 모르겠습니다. 여기에 내 코드가있다. 나는 $this->comparator을 시도하고 그 didnt 도움. comparator이 클래스의 멤버 변수에 액세스 할 필요가없는 함수 인 경우 간단합니다.PHP의 소트 비교 함수가 클래스 멤버 변수에 대한 액세스 필요 -

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 
    } 
} 

답변

7

당신은 callable 방법으로 정렬 기능을 지정해야합니다

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

가 호출 유형은 PHP 5.4 이전에 존재하지 않았지만, 방법을 참조하면 같은 방식으로 작동합니다.

관련 문제