phpanonymous-functionzend-certification

php Anonymous function


When I was reading questions for Zend Certified PHP Engineer 5.5 I saw question about anonymous function but I need to explan how it work.

function z($x)
{
    return function($y) use ($x)
    {
        return str_repeat( $y , $x );
    };
}

$a = z(2);
$b = z(3);

echo $a(3).$b(2);

The output for this code is:

33222

But in function header there is only $x parameter from where $y got there value!


Solution

  • Function z creates and returns a new function, but an anonymous one. That new function is defined so that it has one argument - $y. However, this anonymous function also uses argument $x from a function z.

    To make it simple, function z basically creates a function which can repeat any string, but a fixed number of times. The number of times a string is repeated is determined by the value of argument $x in z.

    So, calling z(2) creates a new function which is functionally equivalent to writing

    function repeat_two_times($y) {
        return str_repeat($y, 2);
    }
    

    In you example, hard coded value 2 is determined by the value of $x.

    You can read more about this in the documentation. The principle displayed by the example can be quite useful for creating partial functions like add5, inc10, ...