如何在usort/uasort cmp函数中添加其他参数?

Rie*_*ing 6 php

我想在compare_by_flags函数中使用这个$ sort_flags数组,但我没有找到方法,是否可能?

public function sort_by_rank(array $sort_flags = array()) {
    uasort($this->search_result_array, array($this, 'compare_by_flags'));
}

private static function compare_by_flags($a, $b) {
    // I want to have this $sort_flags array here to compare according to those flags      
}
Run Code Online (Sandbox Code Playgroud)

zer*_*kms 7

如果你使用php <5.3那么你可以使用实例变量:

public function sort_by_rank(array $sort_flags = array()) {
    $this->sort_flags = $sort_flags;
    uasort($this->search_result_array, array($this, 'compare_by_flags'));
}

private static function compare_by_flags($a, $b) {
    // I want to have this $sort_flags array here to compare according to those flags      
}
Run Code Online (Sandbox Code Playgroud)

否则 - 使用闭包:

public function sort_by_rank(array $sort_flags = array()) {
    uasort($this->search_result_array, function($a, $b) use ($sort_flags) {
        // your comparison
    });
}
Run Code Online (Sandbox Code Playgroud)