Sorting using the create_function comparator in PHP prior to 5.3?

I had not used anonymous functions in PHP before, but I found a piece of code that uses it to sort objects

usort($numTurnsPerUser,build_sorter('turns'));

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

This code will sort the object using the key (I go to the "queue"). For example, an object that looks like this: (written in JSON, for readability only)

$numTurnsPerUser = {
    "31":{
        "turns":15,
        "order":0
    }, "36":{
        "turns":12, 
        "order":1
    }, "37":{
        "turns":14, 
        "order":2
    }
}

will be sorted into an object that looks like this:

$numTurnsPerUser = {
    "36":{
        "turns":12,
        "order":1
    }, "37":{
        "turns":14,
        "order":2
    }, "31":{
        "turns":15, 
        "order":0
    }
}

This works fine on my local server running PHP 5.3.0, but it doesn’t work on my online server running php5. I can not find any information other than this. I get an error

Parse error: syntax error, unexpected T_FUNCTION

, PHP < 5.3 create_function, "" . - , "" , , "" create_function?

+5
2

:

Class Sorter {
  private $key;

  public function __construct($key) {
    $this->key = $key;
  }

  public function sort($a, $b) {
    return strnatcmp($a[$this->key], $b[$this->key]);
  }
}

usort($numTurnsPerUser, array(new Sorter('key_b'), 'sort'));
+3

( create_function):

function build_sorter($key) {
    return create_function('$a, $b', '$key = '.var_export($key, true).';
        return strnatcmp($a[$key], $b[$key]);
    ');
}

, , , create_function, , . , .

0

All Articles