【问题标题】:PHP - Assign an anonymous function to a variable inside of its own function and use it [closed]PHP - 将匿名函数分配给其自身函数内的变量并使用它[关闭]
【发布时间】:2019-06-05 09:40:27
【问题描述】:

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

function func() {

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

    $call();

}

但它抛出一个错误说:

函数名必须是字符串

我也试过这样调用函数:

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

而且效果也不太好。

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

编辑

好像是原代码有问题,我写的例子中没有

这是我的真实代码:

$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 function php-7 php-7.0


【解决方案1】:

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

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

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

和

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

改编自https://stackoverflow.com/a/2480242/2681964

【讨论】:

  • 很好的答案,谢谢。
  • @FightRay 如果成功了,您能否将此标记为已接受的答案?这有助于我的声誉,你的声誉以及这对后来来到这里的人有用的事实:)
  • 是的,当然,我做到了。有人声称可能重复的另一个问题与我的甚至不相似......我认为我的问题很有帮助,因为我在谷歌中找不到任何此类事件的转折,我很好地解释了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 2017-12-19
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
  • 2020-05-20
相关资源
最近更新 更多