I had no idea something like this (javascript-esque inline function) would work in PHP. As someone who spends a lot of time writing javascript/jquery, I was pretty stunned when my ‘i wonder if this will work’-attempt actually worked.
usort($inbox_messages, function($a, $b){
return strtotime($b["date"]) - strtotime($a["date"]);
});
Now, is there anything I should know about implementations like that? Performance issues, backwards compatibility, scope etc.
Is this common practice, or bad code?
This feature is called anonymous functions, and it becomes available since PHP 5.3:
There’s a (slight) difference in scope resolution as well for them:
So, in this example:
… from that documentation page both
$taxand$totalare effectively injected into aclosure($callback) scope without usingglobalkeyword.Anonymous functions are in fact objects of Closure class. And it’s not just an implementation feature: as (since PHP 5.4) these functions can use
$thisobject (similar to a context object in JavaScript), there are some useful methods that can change this context (Closure::bind, Closure::bindTo – compare these with Function.bind, for example).Speaking more specifically, it’s actually a good practice using anonymous functions when
map/filter-ing collection, as these functions won’t go into the global scope. But, of course, it’s not a solution if you need your code to work on PHP 5.2.