如果您需要在呼叫方法中使用帶有鍵值的 usort,我將其寫成一個實用程式
<?php
function usort_comparison($obj, $method, $key) {
$usorter = &new Usort($obj, $method, $key);
return array($usorter, "sort");
}
class Usort {
function __construct($obj, $method, $key) {
$this->obj = $obj;
$this->method = $method;
$this->key = $key;
}
function sort($a, $b) {
return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key));
}
}
?>
<?php
require_once("util/usort.php");
class Foo {
$items = array(FooBar(13), FooBar(2));
public function sorter() {
usort($this-items, usort_comparison("Foo", "_cmp", "item"));
}
public static function _cmp($a, $b, $key) {
return strcasecmp($a->$key, $b->$key);
}
}
class FooBar {
public $item;
function __construct($val) {
$this->item = $val;
}
}
?>
~ 簡單的範例... 但在我需要使用的方式中,關鍵字是用在 switch 語句中,以動態選擇要比較的物件的不同成員(例如,依 x 或 y 或 z 排序)。