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

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?

+4
2

, $.

:

private $breadcrumbs = array();
private $siteroot;
private $navigation;

function buildBreadcrumbs($elements, $parentID){
    if($this->siteroot['id'] === $parentID){
        $nav = array_values($this->navigation);
        array_unshift($this->breadcrumbs, array('label' => 'Start', 'id' => $nav[0]['id']));
    } else {
        foreach ($elements as $element) {
            if ($element['id'] === $parentID) {
                array_unshift($this->breadcrumbs, array('label' => $element['navlabel'], 'id' => $element['id']));
                buildBreadcrumbs($elements, $element['parent'][0]);
            }
        }
    }
}

, . , ( $.)

0

, .

:

$global = 123;
function parent() {
   $parent = 123;
   $closure = function() use ($parent, $global) {
      // $global won't exist, but $parent will.
   }
}

"" , .

. , , , . - ,

. № 4 : http://php.net/manual/en/functions.anonymous.php

0

Source: https://habr.com/ru/post/1680511/


All Articles