php函数参数为数组,PHP函数 以引用方式传递数组

各位大神,《PHP从入门到精通》中,讲对数组变量按引用传递时,只是传递了数组首个元素的地址。因此退出函数后,只有对首个元素的修改是有效的。请看如下代码,整个数组中的所有元素都改了。为什么呢?

调用函数之前,我的名字叫 :'.$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从入门到精通》中,讲对数组变量按引用传递时,只是传递了数组首个元素的地址。 因此退出函数后,只有对首个元素的修改是有效的。

?色部分明?是?的。

看完?,??,??一下。

谢谢了。

书上错的真离谱。

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值