2013-10-28 141 views
0

如果我們使用遞歸函數調用如何爲變量分配內存。當運行下面的代碼時,它的回聲2作爲結果。任何人都可以請指導爲什麼$ a的值沒有采取任何循環迭代。 如果我設置函數調用時遞歸函數調用值不保留函數調用時

$a= recursionfunction($a); 

與在函數中它將工作正常。

function recursionfunction($a) 
{ 
    if($a<10) 
    { 
     $a=$a+1; 
     recursionfunction($a); 

    } 
    return $a; 

} 
$result = recursionfunction(1); 
echo $result 
+0

$ result = abc(1); - 顯然你有一些複製和粘貼奇怪的事情。 –

+0

你的'if'部分不會返回任何東西。另外,我們可以安全地假設'abc()'和'recursionfunction()'是一樣的嗎? – geomagas

回答

1

假設你的意思recursionfunction(1)而不是abc(1),你在你的函數缺少return

function recursionfunction($a) 
{ 
    if($a<10) 
    { 
     $a=$a+1; 
     return recursionfunction($a); 
// missing -^ 
    }else{ 
     return $a; 
    } 

} 
$result = recursionfunction(1); 
echo $result 

編輯

你(實質性)編輯後,整個情況是不同的。 讓我們通過線的功能線,看看,會發生什麼:

// at the start $a == 1, as you pass the parameter that way. 

// $a<10, so we take this if block 
    if($a<10) 
    { 
     $a=$a+1; 
// $a now holds the value 2 

// call the recursion, but do not use the return value 
// as here copy by value is used, nothing inside the recursion will affect 
// anything in this function iteration 
     recursionfunction($a); 
    } 

// $a is still equal to 2, so we return that 
    return $a; 

更多細節可以在這個問題上找到:Are PHP Variables passed by value or by reference?

也許你再次,要添加一個額外的return聲明,以實際上使用遞歸的值:

function recursionfunction($a) 
{ 
    if($a<10) 
    { 
     $a=$a+1; 
     return recursionfunction($a); 
// add ---^ 
    } 
    return $a; 
}