[英]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.