[英]Error when calling function inside the function
我正在制作一个具有多种功能的课程。 有一件事让我感到困惑,那就是当我在函数中调用函数本身时:
在以下函数中,当我在函数内部调用 getChildKey 函数时,我没有收到错误消息:
function getChildKey1($FPTree)
{
function getChildKey($FPTree){
$result = [];
if (isset($FPTree['child'])){
foreach ($FPTree['child'] as $key => $value){
$result[$key]=getChildKey($value);
}
}
if (empty($result)){
return 'gak ada array';
}
return $result;
}
$output = [];
foreach ($FPTree as $index => $child){
$output[$index]=getChildKey($child);
}
return $output;
}
当我尝试创建一个类似于getChildKey
函数的函数时出现错误,该函数在其中调用函数本身:
function pathFinder($arr = [], $needle)
{
$path = '';
$paths = [];
foreach ($arr as $key => $value) {
if (is_array($value)) {
$path .= $key . "->";
pathFinder($value, $needle); //error here
} else {
if ($key === $needle) {
$paths[] = $path . $key;
}
}
}
return $paths; // return all found paths to key $needle
}
为什么会这样? 我必须做什么才能使pathFinder
函数可以在其中调用自己?
当您定义一个函数并在那个时候调用它时(如果找到了函数),php 会为在其中声明/定义的所有变量和函数创建一个范围,该范围就像一个不同的“房子”。 这就是我们有时需要使用关键字global
的原因,当我们想要引用在函数外部定义的$var1
(和类,如果有的话)并且我们碰巧在我们的函数中声明了一个同名的变量
情况1:
function A($args1)
{
//---- scope of A starts here
function B($args2)
{ return 'hello from B'; }
B(); // call B
//---- scope of A ends here
}
案例2:
function A($args1)
{
//---- scope of A starts here
A(); // call A
//but where is A?
//---- scope of A ends here
}
在第一种情况下,A 函数的块({} 之间的任何内容)是自包含块,这意味着它拥有内部代码运行所需的一切。 那么当遇到B()
时 php 在A
的范围内查找,是否定义了名为B
的函数? 是的!
在第二种情况下,PHP 在遇到A()
时会做同样的事情,但在那里找不到它,它会在全局范围内查找,即。 用于查找名为A
的函数的类之外的所有代码。 因为没有它抛出一个未找到的异常
当你使用$this->A()
php 知道在哪里寻找这个函数,即在调用它的同一个对象中,它运行得很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.