Yes you can in php 5.3 or above, you can read the documentation here:
http://php.net/manual/en/functions.anonymous.php
It doesn't work exactly like JavaScript tough. JavaScript is a prototypal language, php is not.
You can do this in JavaScript:
var value = 'foo';
object.doSomething(function () {
console.log(value);
});
You can do that because JavaScript functions has a reference to it's creator. In php you cannot. The value would be out of scope.
Other than that, it works kind of similar.
For example, if you want to make dynamic iterations over arrays or other structures.
function iterateOverArray($array, $function) {
foreach ($array as $key => $value) {
$function($key, $value);
}
}
That function allows you to iterate over an array and specify your own action. For example:
$array = array('foo', 'bar', 'FOBAR');
iterateOverArray($array, function ($key, $value) {
echo $key . ' => ' . $value;
});
This is very useful to modify complex structures. But that's the only situation I've used anonymous functions in php. But maybe that's because it's still kind of new in php.