Why can't I use 'use' in non-anonymous functions?

Viewed 225

I'm trying to create a path from an array of parent-child elements.

The idea was to write a recursive function, which fills up an array with all the elements the path contains in order.

My problem is with closure in PHP:

To get my recursive function to work, I had to define several variables in the global scope.

This is how 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 in this way:

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 syntax error:

PHP Parse error: syntax error, unexpected T_USE, expecting '{'

What am I doing wrong here?

Why does $breadcrumbs have to be global in the first place so the function can use it?

2 Answers
Related