2014-04-16 34 views
1
<?php 
    function a($n){ 
    return (b($n) * $n); 
    } 

    function b(&$n){ 
    ++$n; 
    } 

    echo a(5); 

    ?> 

我做了一個考試這個星期天,想知道爲什麼輸出此代碼是0爲什麼在php中給出0?

我不是開發人員在PHP中,所以任何幫助,將不勝感激。

+7

當我運行它,我得到36 – KevBot

+3

可以驗證,[看演示](http://codepad.org/E4aIlOOn) – Kermit

+1

它將0爲一個(-1),否則不能 –

回答

7

■如果您在b返回值

int(0) 

一切都會好得很他的代碼給出0,因爲它缺少return。與下面哪個(如圖所示更正時)產生36相比較,如其他答案中所述。

function a($n){ 
    // Since b($n) doesn't return a value in the original, 
    // then NULL * $n -> 0 
    return (b($n) * $n); 
} 

function b(&$n){ 
    // But if we return the value here then it will work 
    // (With the initial condition of $n==5, this returns 6 AND 
    // causes the $n variable, which was passed by-reference, 
    // to be assigned 6 such that in the caller 
    // it is 6 * $n -> 6 * 6 -> 36). 
    return ++$n; 
} 

echo a(5); 

如何function b(&$n)作品見上文Passing by Reference;如果簽名是function b($n),結果將會是30.

+1

爲什麼是-1?這是正確的......缺乏回報使得它返回null。 +1 –

+1

這是正確的。 +1。 'b'當然會改變'$ n'的值,但不會帶來OP假設我假設的改變後的值(不返回)。 – Lekhnath

+0

@Lekhnath根據其他答案,變量仍然發生變化。這就是爲什麼結果是36,而不是30. – user2864740

3
function a($n) { 
    return (b($n) * $n); 
} 

function b(&$n){ 
    ++$n; 
} 

echo a(5); 

這是當你調用echo a(5);(不是實際的順序,它只是爲了演示)會發生什麼:

return (b($n) * $n); 

此return語句有兩個部分:b($n)$nb($n)是對函數b的調用。函數b通過引用接受其參數並將值增加1。請注意,它不返回值

由於它沒有返回值,因此b($n)將是NULL。證明:

function a($n){ 
    $v = b($n); 
    var_dump($v); 
    return (b($n) * $n); 
} 

輸出:

NULL 

在接下來的步驟中,您繁衍b($n)$n的結果(這是NULL)(相等於6)。

所以結果是NULL * 0。結果是什麼?使用var_dump()

var_dump(NULL * 6); 

輸出:

function a($n){ 
    return (b($n) * $n); 
} 

function b(&$n){ 
    return ++$n; 
} 

echo a(5); 

輸出:

36 
2

默認情況下,在PHP中,return語句等於NULL/0.因此,即使b()函數通過引用更改了n的值, return語句等於null。 然後,當您將此返回語句乘以(等於零)任意數字時,它將等於零。

嘗試在b()定義的末尾添加'return 1',結果應該等於n

相關問題