php 和 javascript 执行嵌套函数的区别

Difference between how php and javascript execute a nested function

我正在尝试想象 javascript 和 php 如何处理嵌套函数。

重点是:

php:

b(); //CANNOT call b at this point because isn't defined yet
a(); //CAN call a at this point because the interpreter see the declar
b(); //ok now i can call b, because the interpreter see the declaration after a execution
function a(){
    function b(){
        echo "inner";
    }
}

同时 javascript:

b(); //CANNOT call b isn't defined yet
a(); //CAN call a at this point because the interpreter see the declar

function a(){
    function b(){
        console.log("inner");
    }
}
a(); //ok now i can call a because is defined
b(); // **CANNOT** call b yet !!   

为什么在 javascript 中即使执行了 a 也无法调用 b()? PHP 有什么不同之处?

提前致谢!

这是一个范围的事情。你可以很容易地 - 在 javascript - 写成 "var b = function()"。 "b"只是在函数a的范围内定义的函数类型的变量。在PHP中,"a"和"b"都是全局函数,但是定义"b"是函数"a"的工作,所以直到"a" 被调用。考虑这个例子...

function a($x) {
    if ($x) {
        function b() { echo "x not empty"; }
    } else {
        function b() { echo "x empty"; }
    }
}
a(1);    // Defines function b
b();     // x not empty
a(0);    // PHP Fatal error:  Cannot redeclare b() (previously declared...

您可以从重新定义 "b" 的失败中看出,"b" 是一个真正的全局作用域函数。 Function "a" 可以使用各种标准来定义函数以用于不同运行中的特定目的。显然,在这种情况下,在函数 "a" 决定如何定义它之前调用函数 "b" 是没有意义的。

顺便说一句,我不认为上面的示例是很好的编码实践,但它确实说明了这一点。

与您的 javascript 代码最相似的 PHP 代码是:

function a() {
    $b = function() {
            echo "'b' says inner";
         };
    $b();    // Demonstrating the function can be used inside "a"
}
a();    // 'b' says inner

$b是函数类型的变量,只能在函数内部使用"a".