You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向usort调用的非内联比较函数传递变量?

向usort的独立比较函数传递变量的几种方法

当你需要保留独立的大型比较函数,同时要给它传递外部变量时,有这几种实用方案:

1. 用闭包包裹独立函数(最推荐)

先把复杂的比较逻辑单独定义成函数,然后通过闭包把外部变量传进去,再在闭包里调用这个独立函数:

// 单独定义的大型比较函数
function customCompare($a, $b, $sortKey) {
    // 这里写你的复杂比较逻辑,比如按指定键排序
    return strcmp($a[$sortKey], $b[$sortKey]);
}

// 要传递的外部变量
$targetKey = 'username';

// 用闭包把变量传给usort
usort($arr, function($a, $b) use ($targetKey) {
    return customCompare($a, $b, $targetKey);
});

这种方式既保留了独立函数的可读性,又能灵活传递变量,不会污染全局环境。

2. 借助类的属性传递变量

如果你的排序逻辑需要和多个状态绑定,或者要复用排序规则,可以把比较函数放到类里,用类属性存储变量:

静态方法版本

class SortHelper {
    private static $currentSortKey;

    // 设置要传递的变量
    public static function setSortKey($key) {
        self::$currentSortKey = $key;
    }

    // 独立的比较函数
    public static function compare($a, $b) {
        return strcmp($a[self::$currentSortKey], $b[self::$currentSortKey]);
    }
}

// 使用时先设置变量,再调用usort
SortHelper::setSortKey('age');
usort($arr, ['SortHelper', 'compare']);

实例方法版本

class SortHelper {
    private $sortKey;

    // 通过构造函数传入变量
    public function __construct($key) {
        $this->sortKey = $key;
    }

    // 独立的比较函数
    public function compare($a, $b) {
        return strcmp($a[$this->sortKey], $b[$this->sortKey]);
    }
}

// 创建实例时传入变量,再把实例方法传给usort
$sortHelper = new SortHelper('score');
usort($arr, [$sortHelper, 'compare']);

3. 使用全局变量(不推荐)

如果是简单场景,也可以直接用全局变量传递,但这种方式会增加代码耦合,大型项目尽量不用:

// 定义全局变量
$globalSortKey = 'id';

// 独立的比较函数,引用全局变量
function compare($a, $b) {
    global $globalSortKey;
    return strcmp($a[$globalSortKey], $b[$globalSortKey]);
}

// 调用usort
usort($arr, 'compare');

内容的提问来源于stack exchange,提问作者HealerLolCat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:18:11