您好,欢迎访问一九零五行业门户网

PHP函数 以引用方式传递数组

各位大神,《php从入门到精通》中,讲对数组变量按引用传递时,只是传递了数组首个元素的地址。因此退出函数后,只有对首个元素的修改是有效的。请看如下代码,整个数组中的所有元素都改了。为什么呢?
$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从入门到精通》中,讲对数组变量按引用传递时,只是传递了数组首个元素的地址。 因此退出函数后,只有对首个元素的修改是有效的。
?色部分明?是?的。
看完?,,一下。
谢谢了。
书上错的真离谱。
其它类似信息

推荐信息