Is it possible to simulate closures in PHP 5.2.x not using globals?

前端 未结 4 1002
抹茶落季
抹茶落季 2020-12-17 22:38

Is it possible to simulate closures in PHP 5.2.x not using globals? I could think of a way that would pass the desired variables as extra parameters to the closure but that

4条回答
  •  难免孤独
    2020-12-17 22:49

    There are some special cases where you can do it.

    If you need to capture a variable by value (not by reference), and the value is a simple value type like a number, string, or array of the above (not reference types like objects and resources and functions), then you can simply insert it into the function definition using var_export():

    $var = array(1, 3);
    $f = create_function('',
        '$var=' . var_export($var,true) . '; return $var;');
    

    If you need to capture the variable by reference in order to maintain mutable state across calls of the function, but you don't need to have the changes reflected in the original scope where it's created (e.g. to create an accumulator, but the changes to the sum don't need to change the sum variable in the creating scope), then you can similarly insert it, but as a static variable:

    function make_accumulator($sum) {
        $f = create_function('$x',
            'static $var=' . var_export($var,true) . '; return $var += $x;');
        return $f;
    }
    

提交回复
热议问题