Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

anonymous function


Rubyjavascriptにもありますね。create_functionのシンタックスシュガーっぽい気もしましたが、本家の開発者の皆さんには好評のようです。


In the past, people have been told to use the travesty that is
create_function() to emulate this kind of behavior, well, it turns
out to be a minor patch to the parser to pull that into the core.

たとえば、

<?php
$data = array("zoo", "orange", "car", "lemon", "apple");
usort($data, function($a, $b) { return strcmp($a, $b); });
var_dump($data);
echo "\n";
?>

のようなコードで、

array(5) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(3) "car"
  [2]=>
  string(5) "lemon"
  [3]=>
  string(6) "orange"
  [4]=>
  string(3) "zoo"
}

が出力されます。