php自訂函數間的值傳遞/引用傳遞用法詳解

來源:互聯網
上載者:User
php:函數間的參數傳遞

1.值傳遞

<?php function exam($var1){ $var1++; echo "In Exam:" . $var1 . "<br />"; } $var1 = 1; echo $var1 . "<br />"; exam($var1); echo $var1 . "<br />"; ?>

-------------------------------------------------------------------------------
輸出結果:
1
In Exam: 2
1
-------------------------------------------------------------------------------
2.引用傳遞

<?php function exam( &$var1){ $var1++; echo "In Exam:" . $var1 . "<br />"; } $var1 = 1; echo $var1 . "<br />"; exam($var1); echo $var1 . "<br />"; ?>

-------------------------------------------------------------------------------
輸出結果:
1
In Exam: 2
2
-------------------------------------------------------------------------------
3.選擇性參數

function values($price, $tax=""){ $price += $prive * $tax; echo "Total Price:" . $price . "<br />"; } values(100, 0.25); values(100);

輸出結果:
Total Price: 125
Total Price: 100
-------------------------------------------------------------------------------
4.如果傳入的是一個對象,可以更改該對象的值
(實際上變數$obj記錄的是這個對象的控制代碼,將$obj作為參數傳入,完全可以對原對象進行操作。)

<?php class Obj{ public $name; public $age; public $gander; public function construct($name, $age, $gander){ $this->name = $name; $this->age = $age; $this->gander = $gander; } public function show_info(){ echo $this->name . " " . $this->age . " " . $this->gander . "<br />"; } } function grow($obj){ $obj->age++; } function test(){ $obj = new Obj("Mr. zhan", "12", "male"); $obj->show_info(); grow($obj); $obj->show_info(); grow($obj); $obj->show_info(); } test(); ?>

-------------------------------------------------------------------------------
輸出結果:
Mr. zhan 12 male
Mr. zhan 13 male
Mr. zhan 14 male

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.