I have the following functions. Wordpress functions, but this is really a PHP question. They sort my $term
objects according to the artist_lastname
property in each object's metadata.
I want to pass a string into $meta
in the first function. This would let me reuse this code as I could apply it to various metadata properties.
But I don't undertstand how I can pass extra parameters to the usort callback. I tried to make a JS style anonymous function but the PHP version on the server is too old and threw a syntax error.
Any help - or a shove towards the right corner of the manual - gratefully appreciated. Thanks!
function sort_by_term_meta($terms, $meta)
{
usort($terms,"term_meta_cmp");
}
function term_meta_cmp( $a, $b )
{
$name_a = get_term_meta($a->term_id, 'artist_lastname', true);
$name_b = get_term_meta($b->term_id, 'artist_lastname', true);
return strcmp($name_a, $name_b);
}
In PHP, one option for a callback is to pass a two-element array containing an object handle and a method name to call on the object. For example, if
$obj
was an instance of classMyCallable
, and you want to call themethod1
method ofMyCallable
on$obj
, then you can passarray($obj, "method1")
as a callback.One solution using this supported callback type is to define a single-use class that essentially acts like a closure type:
I think this question deserves an update. I know the original question was for PHP version 5.2, but I came here looking for a solution and found one for newer versions of PHP and thought this might be useful for other people as well.
For PHP 5.3 and up, you can use the 'use' keyword to introduce local variables into the local scope of an anonymous function. So the following should work:
Some more general code
If you want to sort an array just once and need an extra argument you can use an anonymous function like this:
If you need a reusable function to sort an array which needs an extra argument, you can always wrap the anonymous function, like for the original question:
The docs say that
create_function()
should work on PHP >= 4.0.1. Does this work?This won't help you at all with
usort()
but might be helpful nevertheless. You could sort the array using one of the other sorting functions,array_multisort()
.The idea is to build an array of the values that you would be sorting on (the return values from
get_term_meta()
) and multisort that against your main$terms
array.Assuming you've access to objects and static (PHP 5 or greater), you can create an object and pass the arguments directly there, like so:
Assuming you don't have access to objects/static; you could just do a global: