dongtao9887 2018-03-28 15:49
浏览 45
已采纳

在定义之前调用嵌套的用户定义函数

According to PHP manual calling a user-defined function prior to its definition doesn't produce an error except:

When a function is defined in a conditional manner... Its definition must be processed prior to being called.

Example:

bar();
$makefoo = true;
if ($makefoo) {
    function bar() {
        echo "I don't exist.
";
    }
}

Throws a Fatal error:

Fatal error: Uncaught Error: Call to undefined function bar() in...

With above explanation I suppose below code to produce the same error:

foo();
bar();
function foo() {
    $makefoo = true;
    if ($makefoo) {
        function bar() {
            echo "I don't exist until foo() is called.
";
        }
    }
}

But it doesn't. What am I missing in manuals that describes this behavior?

  • 写回答

1条回答 默认 最新

  • duanhuchang5056 2018-03-28 15:53
    关注
    foo();
    bar();
    function foo() {
        $makefoo = true;
        if ($makefoo) {
            function bar() {
                echo "I don't exist until foo() is called.
    ";
            }
        }
    }
    

    PHP code is executed in two passes: first the parsing and compilation step, then the runtime. Plain functions like foo can be defined at parse time; they're unconditional and not dependent on runtime information.

    So function foo is defined at parse time, then at runtime foo() is called, which creates function bar, so then you can call bar() right afterwards.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向