PHP - 将匿名函数分配给其自身函数内部的变量并使用它

PHP - Assign an anonymous function to a variable inside of its own function and use it

所以我正在尝试做这样的事情:

function func() {

    $call = function() {
        ...
    };

    $call();

}

但是它抛出一个错误说:

Function name must be a string

我也试过这样调用函数:

$this->call();
call(); // and like this

而且效果不佳。

我不能做我正在做的事情有什么原因吗?

编辑

It seems to be a problem with the original code, and not in the example I wrote

这是我的真实代码:

$data = [...];
$menu_array = [];
$getChildren = function($id) {
          $children = [];
          foreach ($data as $node) {
              if ($id == $node["parent"]) {
                  array_push($children, $node);
              }
          } 
          return empty($children) ? null : $children;
        };

        $check = function($arr, $dat) {
            foreach ($dat as $node) {
                $children = $getChildren($node["id"]);
                if ($children == null) {
                    $arr[$node["display_name"]] = $node["model"];
                } else {
                    $arr[$node["display_name"]][] = $children;
                    $check($children);
                }
            }
        };
$check($menu_array, $data);

这一行抛出错误:

$children = $getChildren($node["id"]);

这里你要做的,就是递归! 问题是,PHP 不会自动将外部作用域中的任何变量添加到函数作用域中。在您的代码 $check($children); 中,实际上未定义变量 $check

您可以通过告诉 PHP 它应该使用函数外部的 $getChildren$check 变量来解决这个问题:

$getChildren = function($id) use (&$getChildren) {
   ...

$check = function($arr, $dat) use (&$check, &$getChildren) {
  ...

改编自