一开始,当学习什么是通过引用传递时,它并不明显......
这是一个示例,希望您能更清楚地了解按值传递和按引用传递的区别是什么...
<?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
}
?>