在 PHP 函数内调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6479211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:30:24  来源:igfitidea点击:

Call function within a function PHP

php

提问by theHack

1    function foo($i){
2       return bar($i)*4;
3       function bar($i){
4           return $i*4;
5           }
6       }
7    echo foo(4);

return

返回

Fatal error: Call to undefined function bar() in /var/www/index.php on line 2

why doesn't it work? it works well in javascript, while it works when i do this:

为什么不起作用?它在 javascript 中运行良好,而当我这样做时它运行良好:

function foo($i){
   return bar($i)*4;
   }

function bar($i){
   return $i*4;
   }

回答by Percy

Define the function above your return value, otherwise it never gets executed.

在返回值上方定义函数,否则它永远不会被执行。

<?php
function foo($i){
    function bar($i){
        return $i*4;
    }
    return bar($i)*4;
}
echo foo(4);
?>

回答by vascowhite

It doesn't work as you are calling bar() before it has been created. See example 2 here:- http://www.php.net/manual/en/functions.user-defined.php

当您在创建 bar() 之前调用它时,它不起作用。请参阅此处的示例 2:- http://www.php.net/manual/en/functions.user-defined.php

回答by Tarek

If you define function within another function, it can be accessed directly, but after calling parent function. For example:

如果在另一个函数中定义函数,则可以直接访问它,但需要调用父函数。例如:

function a () {
    function b() {
    echo "I am b.";
   }
echo "I am a.<br/>";
}
//b(); Fatal error: Call to undefined function b() in E:\..\func.php on line 8
a(); // Print I am a.
b(); // Print I am b.

回答by maaudet

Your code never reach function bar(...), therefore it's never defined.

您的代码永远不会到达function bar(...),因此它永远不会被定义。

You need to put your bar()function before your foo()or before the return bar. (Answer based on your first example).

您需要将您的bar()功能放在您的之前foo()或之前return bar。(答案基于您的第一个示例)。

With your second example you probably define bar()before you use foo()therefore bar()is defined and it works fine.

对于您的第二个示例,您可能bar()在使用之前定义,foo()因此bar()已定义并且它工作正常。

So as long as you have your function defined when you hit a certain spot in your code it works fine, no matter if it's called from within another function.

因此,只要您在代码中的某个位置定义了函数,它就可以正常工作,无论它是否从另一个函数中调用。

回答by Rajasekar Gunasekaran

Execution not execute after return statement

return语句后执行不执行

change your code like this

像这样改变你的代码

 function foo($i){
 function bar($i){
  return $i*4;
 }
 return bar($i)*4;     
}
echo foo(4);