How to add additional parameters to usort/uasort cmp function?
I would like to have this $sort_flags array available within the compare_by_flags function, but I did开发者_开发问答n't find a way to this, is it possible?
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
}
If you use php < 5.3 then you can just use instance variables:
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
}
otherwise - use closures:
public function sort_by_rank(array $sort_flags = array()) {
uasort($this->search_result_array, function($a, $b) use ($sort_flags) {
// your comparison
});
}
You don't mention what you want to achieve by passing the $sort_flags
variable, but you might find this answer of mine useful (either as it stands, or as an example if you want to achieve something different).
You could set it as class static property, like this:
public function sort_by_rank(array $sort_flags = array()) { self::$_sort_flags = $sort_flags; uasort($this->search_result_array, array($this, 'compare_by_flags')); } private static function compare_by_flags($a, $b) { // Read self::$_sort_flags // I want to have this $sort_flags array here to compare according to those flags }
Also you could try this, as of PHP 5.3
uasort($array, function($a, $b) { self::compare_by_flags($a, $b, $sort_flags); });
精彩评论