<slide title="Closures">

<break lines="1" />

<blurb fontsize="4em">http://php.net/closures</blurb>

<example fontsize="1.4em" result='1' title=""><![CDATA[<?php
$data = array(3,2,8,5,6,1,7,4,9);
usort($data, 
             function($a,$b) { 
                 if($a%2==$b%2) return $a>$b;
                 return ($a%2) ? 1 : -1;
             }
     );
foreach($data as $v) echo "$v ";]]></example>

<break lines="1" />

<example fontsize="1.4em" result='1' title=""><![CDATA[<?php
$getClosure = function($v) {
    return function() use($v) {
        echo "Hello World: $v!\n";
    };
};

$closure = $getClosure(2);
$closure();]]></example>

<break lines="1" />

<blurb fontsize="4em">Remember closures are early-binding</blurb>
<example fontsize="1.4em" result='1' title=""><![CDATA[<?php
function getMsgFnc() {
    global $msg;
    return function() use ($msg) {
        echo "Msg: {$msg}!<br/>\n";
    };
}

$GLOBALS['msg'] = "Hello";
$fnc = getMsgFnc();
$fnc();
$GLOBALS['msg'] = "World";
$fnc();
]]></example>

<break lines="1" />

<blurb fontsize="4em">However, you can do this:</blurb>
<example fontsize="1.4em" result='1' title=""><![CDATA[<?php
function getMsgFnc2() {
    global $msg;
    return function() use (&$msg) {
        echo "Msg: {$msg}!<br/>\n";
    };
}

$GLOBALS['msg'] = "Hello";
$fnc = getMsgFnc2();
$fnc();
$GLOBALS['msg'] = "World";
$fnc();
]]></example>

</slide>
