Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling anonymous function within anonymous function (Inception)

Simple question, but tough answer? I have the following anonymous function inside a class method:

$unnest_array = function($nested, $key) {
    $unnested = array();

    foreach ($nested as $value) {
        $unnested[] = (object) $value[$key];
    }

    return $unnested;
};

In the same class method I have this array, where I save anonymous functions. I.e. I create a new anonymous function using the inline create_function() and I would want to use the already defined anonymous function $unnest_array(). Is it possible?

$this->_funcs = array(
    'directors' => array(
        'func'  => create_function('$directors', 'return $unnest_array($directors, "director");'),
        'args'  => array('directors')
    )
);

At the moment I am getting "Undefined variable: unnest_array". Help?

like image 746
Viktor Avatar asked Feb 25 '26 22:02

Viktor


1 Answers

Why are you using create_function in the first place? Closures replace create_function entirely, leaving it essentially obsolete in all versions of PHP after 5.3. It seems like you're trying to partially apply $unnest_array by fixing the second argument as "director".

Unless I've misunderstood you, you should be able to achieve the same result by using a closure/anonymous function (untested):

$this->_funcs = array(
    'directors' => array(
        'func'  => function($directors) use ($unnest_array)
            {
                return $unnest_array($directors, "director");
            },
        'args'  => array('directors')
    )
);

The use ($unnest_array) clause is necessary to access local variables in the parent scope of the closure.

like image 130
Will Vousden Avatar answered Feb 27 '26 13:02

Will Vousden