È possibile utilizzare non solo una funzione anonima ma una chiusura, come ad es.
e $ sort saranno disponibili nel corpo della funzione. autonomo esempio:
<?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";
}
}
stampe
----- 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
aggiornamento: con PHP < 5.3 è possibile utilizzare un oggetto invece di una funzione anonima. usort() si aspetta che il secondo parametro sia callable
. Questa può essere una funzione anormale a partire da php 5.3, ma può anche essere il nome di una funzione .... o un oggetto e un nome di metodo passati come una matrice come 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')
);
}
(Se si fa largo uso di questo - o non vogliono scrivere scuse come questo -_- - si potrebbe desiderare di definire un'interfaccia come interface Comparator { ... }
, lasciate Foo implementare tale interfaccia ed avere qualche funzione/classe che usa Comparator, cioè un wrapper per gli oggetti intorno a usort().)
Perché non riesce? Che risultato vedi? – codaddict
Nel primo tentativo, $ sort ovviamente non è stato trovato. Nel secondo tentativo, non so come fare riferimento alla funzione 'srt'. – Hubro