note 39124 modified in language.references.pass by danbrown
| From: | danbrown@php.net | Date: | Thu, 28 Jan 2010 13:22:17 +0000 |
| Subject: | note 39124 modified in language.references.pass by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165428@lists.php.net to get a copy of this message | ||
One thing to note about passing by reference. If you plan on assigning the reference to a new
variable in your function, you must use the reference operator in the function declaration as well
as in the assignment. (The same holds true for classes.)
<?php
function f1(&$num) {
$num++;
}
function f2(&$num) {
$num1 = $num;
$num1++;
}
function f3(&$num) {
$num1 = &$num;
$num1++;
}
$myNum = 0;
print("Declare myNum: " . $myNum . "<br />\n");
f1($myNum);
print("Pass myNum as ref 1: " . $myNum . "<br />\n");
f2($myNum);
print("Pass myNum as ref 2: " . $myNum . "<br />\n");
f3($myNum);
print("Pass myNum as ref 3: " . $myNum . "<br />\n");
?>
-------------------------------------------------------
OUTPUT
-------------------------------------------------------
Declare myNum: 0
Pass myNum as ref 1: 1
Pass myNum as ref 2: 1
Pass myNum as ref 3: 2
-------------------------------------------------------
Hope this helps people trying to detangle any problems with pass-by-ref.
--was--
One thing to note about passing by reference. If you plan on assigning the reference to a new
variable in your function, you must use the reference operator in the function declaration as well
as in the assignment. (The same holds true for classes.)
-------------------------------------------------------
CODE
-------------------------------------------------------
function f1(&$num) {
$num++;
}
function f2(&$num) {
$num1 = $num;
$num1++;
}
function f3(&$num) {
$num1 = &$num;
$num1++;
}
$myNum = 0;
print("Declare myNum: " . $myNum . "<br />\n");
f1($myNum);
print("Pass myNum as ref 1: " . $myNum . "<br />\n");
f2($myNum);
print("Pass myNum as ref 2: " . $myNum . "<br />\n");
f3($myNum);
print("Pass myNum as ref 3: " . $myNum . "<br />\n");
-------------------------------------------------------
-------------------------------------------------------
OUTPUT
-------------------------------------------------------
Declare myNum: 0
Pass myNum as ref 1: 1
Pass myNum as ref 2: 1
Pass myNum as ref 3: 2
-------------------------------------------------------
Hope this helps people trying to detangle any problems with pass-by-ref.
http://php.net/manual/en/language.references.pass.php