各位大神,《PHP從入門到精通》中,講對陣列變數按引用傳遞時,只是傳遞了數組首個元素的地址。因此退出函數後,只有對首個元素的修改是有效。請看如下代碼,整個數組中的所有元素都改了。為什麼呢?
/**
* @author blog.anchen8.net
* @copyright 2015
*/
// TEST transmit the parameters by reference
function changeName(&$name)
{
$name='Xiao HuiHui';
}
$girl='Mo';
echo '
調用函數之前,我的名字叫 :'.$girl;
changeName($girl);
echo'
調用函數之後,我的名字叫:'.$girl;
// Test transmit the array parameters by reference
function addPrice(&$price)
{
$price[0]+=20;
$price[1]+=30;
$price[2]+=25;
}
function discount(&$price)
{
foreach ($price as $key=> $aa)
{
$aa*=.8;
$price[$key]*=.8;
}
}
function priceSet(&$price)
{
$price[0]=20;
$price[1]=30;
$price[2]=25;
}
echo '
';
$price_a=array(100,29,30);
echo'
Before Discount the price is ';
var_dump($price_a);
discount($price_a);
echo '
After Discount the price is ';
var_dump($price_a);
$price_a=array(100,29,30);
addPrice($price_a);
echo '
After Add the price is ';
var_dump($price_a);
$price_a=array(100,29,30);
priceSet($price_a);
echo '
After Set the price is ';
var_dump($price_a);
echo '
';
function setInfo (&$people)
{
$people['name']='MoMomo';
$people['age']=20;
$people['hobby']='reading';
}
$gril=array('name'=>'Xiao Mo MO','age'=>18,'hobby'=>'Studing');
echo '
before called the function ,the value is ';
var_dump($gril);
setInfo($gril);
echo '
after called the function ,the array value is ';
var_dump($gril);
?>
運行結果:
調用函數之前,我的名字叫 :Mo
調用函數之後,我的名字叫:Xiao HuiHui
Before Discount the price is array(3) { [0]=> int(100) [1]=> int(29) [2]=> int(30) }
After Discount the price is array(3) { [0]=> float(80) [1]=> float(23.2) [2]=> float(24) }
After Add the price is array(3) { [0]=> int(120) [1]=> int(59) [2]=> int(55) }
After Set the price is array(3) { [0]=> int(20) [1]=> int(30) [2]=> int(25) }
before called the function ,the value is array(3) { ["name"]=> string(10) "Xiao Mo MO" ["age"]=> int(18) ["hobby"]=> string(7) "Studing" }
after called the function ,the array value is array(3) { ["name"]=> string(6) "MoMomo" ["age"]=> int(20) ["hobby"]=> string(7) "reading" }
回複討論(解決方案)
CSDN大法好。小菜鳥求教了。
您不覺得那位作者太想當然了嗎?
這種治學態度寫的書能看嗎?
版主推薦一些差不多的PHP學習書唄。謝謝了。
《PHP從入門到精通》中,講對陣列變數按引用傳遞時,只是傳遞了數組首個元素的地址。 因此退出函數後,只有對首個元素的修改是有效。
?色部分明?是?的。
看完?,??,??一下。
謝謝了。
書上錯的真離譜。