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_functionin the first place? Closures replacecreate_functionentirely, leaving it essentially obsolete in all versions of PHP after 5.3. It seems like you’re trying to partially apply$unnest_arrayby 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):
The
use ($unnest_array)clause is necessary to access local variables in the parent scope of the closure.