6

I would like to have this $sort_flags array available within the compare_by_flags function, but I didn'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      
}
Riesling
  • 6,343
  • 7
  • 29
  • 33

3 Answers3

7

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
    });
}
zerkms
  • 249,484
  • 69
  • 436
  • 539
2

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).

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
-1

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);
});
azat
  • 3,545
  • 1
  • 28
  • 30
  • This exact code will not work, as long as anonymous function variable scope has no idea what `$sort_flags` is. – zerkms Sep 12 '11 at 12:13