您不仅可以使用匿名函数,还可以使用闭包,例如
function ($a,$b) use ($sort) { ... }
并且 $sort 将在函数体中可用。
独立的示例:
<?php
function getFn($sort) {
return function($a, $b) use($sort) {
if($a->$sort > $b->$sort) return 1;
if($a->$sort < $b->$sort) return -1;
return 0;
};
}
$abuseCases = array(
(object)array('ID'=>1, 'Sender'=>'Sender A'),
(object)array('ID'=>3, 'Sender'=>'Sender D'),
(object)array('ID'=>2, 'Sender'=>'Sender C'),
(object)array('ID'=>4, 'Sender'=>'Sender B')
);
echo "\n----- Sort By Sender ----\n";
usort($abuseCases, getFn('Sender'));
foo($abuseCases);
echo "\n----- Sort By ID ----\n";
usort($abuseCases, getFn('ID'));
foo($abuseCases);
function foo($a) {
foreach($a as $o) {
echo $o->ID, ' ', $o->Sender, "\n";
}
}
prints
----- Sort By Sender ----
1 Sender A
4 Sender B
2 Sender C
3 Sender D
----- Sort By ID ----
1 Sender A
2 Sender C
3 Sender D
4 Sender B
Update:在 phpcallable。从 php 5.3 开始,它可以是一个匿名函数,但它也可以是一个函数的名称......或者一个对象和一个作为数组传递的方法名称,例如array($obj, 'methodName')
.
$abuseCases = getData();
echo "\n----- Sort By Sender ----\n";
usort($abuseCases, array(new Foo('Sender'), 'compare'));
foo($abuseCases);
echo "\n----- Sort By ID ----\n";
usort($abuseCases, array(new Foo('ID'), 'compare'));
foo($abuseCases);
class Foo {
public $propName; // protected?
public function __construct($propertyName) {
$this->propName = $propertyName;
}
public function compare($a, $b) {
$prop = $this->propName;
if($a->$prop > $b->$prop) return 1;
if($a->$prop < $b->$prop) return -1;
return 0;
}
}
function foo($a) {
foreach($a as $o) {
echo $o->ID, ' ', $o->Sender, "\n";
}
}
function getData() {
return array(
(object)array('ID'=>1, 'Sender'=>'Sender A'),
(object)array('ID'=>3, 'Sender'=>'Sender D'),
(object)array('ID'=>2, 'Sender'=>'Sender C'),
(object)array('ID'=>4, 'Sender'=>'Sender B')
);
}
(如果你大量使用这个 - 或者不想写这样的借口 -_- - 你可能想定义一个像这样的接口interface Comparator { ... }
,让 Foo 实现该接口并拥有一些使用 Comparator 的函数/类,即 usort() 周围对象的包装器。)