PHP函數 以引用方式傳遞數組

來源:互聯網
上載者:User
各位大神,《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從入門到精通》中,講對陣列變數按引用傳遞時,只是傳遞了數組首個元素的地址。 因此退出函數後,只有對首個元素的修改是有效。
?色部分明?是?的。

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

謝謝了。
書上錯的真離譜。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.