在剛開始的時候學習這不是明擺着....
這裏的,我希望會希望得到您的區別是什麼一個更清晰的認識上按值傳遞,並通過將一個例子什麼引用傳遞參考是...
<?php
$money = array(1, 2, 3, 4); //Example array
moneyMaker($money); //Execute function MoneyMaker and pass $money-array as REFERENCE
//Array $money is now 2,3,4,5 (BECAUSE $money is passed by reference).
eatMyMoney($money); //Execute function eatMyMoney and pass $money-array as a VALUE
//Array $money is NOT AFFECTED (BECAUSE $money is just SENT to the function eatMyMoeny and nothing is returned).
//So array $money is still 2,3,4,5
echo print_r($money,true); //Array ([0] => 2 [1] => 3 [2] => 4 [3] => 5)
//$item passed by VALUE
foreach($money as $item) {
$item = 4; //would just set the value 4 to the VARIABLE $item
}
echo print_r($money,true); //Array ([0] => 2 [1] => 3 [2] => 4 [3] => 5)
//$item passed by REFERENCE
foreach($money as &$item) {
$item = 4; //Would give $item (current element in array)value 4 (because item is passed by reference in the foreach-loop)
}
echo print_r($money,true); //Array ([0] => 4 [1] => 4 [2] => 4 [3] => 4)
function moneyMaker(&$money) {
//$money-array is passed to this function as a reference.
//Any changes to $money-array is affected even outside of this function
foreach ($money as $key=>$item) {
$money[$key]++; //Add each array element in money array with 1
}
}
function eatMyMoney($money) { //NOT passed by reference. ONLY the values of the array is SENT to this function
foreach ($money as $key=>$item) {
$money[$key]--; //Delete 1 from each element in array $money
}
//The $money-array INSIDE of this function returns 1,2,3,4
//Function isn't returing ANYTHING
}
?>
如何閱讀手冊條目的其餘部分? – deceze 2013-05-09 18:51:30
「reference」一詞是指向http://www.php.net/manual/en/language.references.php的鏈接。閱讀。 – Gumbo 2013-05-09 18:51:49