You can use not only anonymous function, but also closure, for example,
function ($a,$b) use ($sort) { ... }
and $ sort will be available in the function body. Do-it-yourself example:
<?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
Update . With php <5.3, you can use an object instead of an anonymous function. usort () expects the second parameter to be callable . It can be an anonymous function like php 5.3, but it can also be the name of a function .... or the object and method name passed as an array like 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') ); }
(If you use this heavily - or don't want to write excuses like this - you can define an interface, for example interface Comparator { ... } , let Foo implement this interface and have some function / class that uses Comparator, that is, a wrapper for objects around usort ().)