PHP 5.3 brought some new interesting stuff, I know its out for a while, but I recently started to love this new functionality. Lambda functions are anonymous functions knows as closures and they are really similar to the closures in JavaScript.
The difference from JS is that variables in the closure don’t have access to variables from outside the function, unless they are brought into the closure by using the “use” keyword.
In following there is a nice example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * Lighten up a color given as hex string with a specific decimal amount * @param string $sHex * @param integer $iAmount * @return string */ public static function lightUpColor($sHex, $iAmount = 50){ $mpDecColors = self::convertHexDecimal($sHex); //convert all values in the mpDecColors array using this function $lighten = function($value) use ($iAmount){ $tmpValue = $value+$iAmount; $tmpValue = $tmpValue>255?255:$tmpValue; return dechex($tmpValue); }; return '#'.implode('',array_map($lighten, $mpDecColors)); } |
The “convertHexDecimal” splits the hex string (i.e. #23ef22) into its color components, converts them to decimal and returns an array(red, green, blue).
Cheers