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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With