I am trying to create a path from an array of parent-child elements.
The idea was to write a recursive function that fills the array with all the elements that the path contains in order.
My closure problem in PHP:
In order for my recursive function to work, I had to define several variables in the global scope.
Here's what it looks like:
global $breadcrumbs;
$breadcrumbs = array();
function buildBreadcrumbs($elements, $parentID){
global $siteroot;
global $breadcrumbs;
global $navigation;
if($siteroot['id'] === $parentID){
$nav = array_values($navigation);
array_unshift($breadcrumbs, array('label' => 'Start', 'id' => $nav[0]['id']));
} else {
foreach ($elements as $element) {
if ($element['id'] === $parentID) {
array_unshift($breadcrumbs, array('label' => $element['navlabel'], 'id' => $element['id']));
buildBreadcrumbs($elements, $element['parent'][0]);
}
}
}
}
I tried using the 'use' keyword instead of globals as follows:
function buildBreadcrumbs($elements, $parentID) use($siteroot, $breadcrumbs, $navigation){
if($siteroot['id'] === $parentID){
$nav = array_values($navigation);
array_unshift($breadcrumbs, array('label' => 'Start', 'id' => $nav[0]['id']));
} else {
foreach ($elements as $element) {
if ($element['id'] === $parentID) {
array_unshift($breadcrumbs, array('label' => $element['navlabel'], 'id' => $element['id']));
buildBreadcrumbs($elements, $element['parent'][0]);
}
}
}
}
But this gives me a syntax error:
PHP Parse error: syntax error, unexpected T_USE, expecting '{'
What am I doing wrong here?
Why $breadcrumbsshould it be global in the first place so that a function can use it?