Skip to content

Instantly share code, notes, and snippets.

@ytkhs
Created January 16, 2011 14:29
Show Gist options
  • Save ytkhs/781831 to your computer and use it in GitHub Desktop.
Save ytkhs/781831 to your computer and use it in GitHub Desktop.
Closure Sample PHP >= 5.3
<?php
# Closure Sample PHP >= 5.3
$var = 'FRESH_';
$func = function($str) use ($var)
{
return $var.strtoupper($str);
};
var_dump($func); // object(Closure)
$func2 = function($str) use (&$var)
{
return $var.strtoupper($str);
};
$var = 'STALE_';
$fruits = array('apple', 'orange', 'grape', 'pear');
var_dump(array_map($func, $fruits));
/*
array(4) {
[0]=>
string(11) "FRESH_APPLE"
[1]=>
string(12) "FRESH_ORANGE"
[2]=>
string(11) "FRESH_GRAPE"
[3]=>
string(10) "FRESH_PEAR"
}
*/
var_dump(array_map($func2, $fruits));
/*
array(4) {
[0]=>
string(11) "STALE_APPLE"
[1]=>
string(12) "STALE_ORANGE"
[2]=>
string(11) "STALE_GRAPE"
[3]=>
string(10) "STALE_PEAR"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment