PHP variable references (&), function references, and object references
1. References to variables
PHP references two variable pointers to the same memory address
$a = "ABC"; $b =& $a, echo $a;//output here: Abcecho $b;//output here: abc$b= "EFG"; echo $a;//Here a value of $ A becomes EFG so the output efgecho $b;//Output EFG here
2. Function reference passing (call to address)
Function test (& $a) {$a = $a +100;} $b =1;echo $b;//Output 1test ($b); Here $b passed to the function is actually the memory address of the variable content of $b, by changing the value of $ A in the function can change the value of the $b echo "
"; echo $b;//Output 101?>
3. A reference to a function returns
function &test () {static $b =0;//declares a static variable $b= $b +1;echo $b; return $b;} $a =test ();//This statement will output $b value of 1$a=5, $a =test ();//This statement will output a value of $b 2$a=&test ();//This statement will output the value of $b 3$a=5; $a =test ();//This statement outputs $ The value of B is 6
The following explanation:
In this way $a=test (); The result is not a function reference return, which is not the same as a normal function call. The reason: It's php's rule.
Calling a function by $a=&test () means that the memory address of the $b variable in the return $b points to the same place as the memory address of the $ A variable
That produces the equivalent effect ($a =& $b;) So changing the value of $ A also changes the value of the $b so that it executes the
4. References to Objects (PHP5)
class Foo {public $bar = 1;} $a = new Foo; $a is actually a reference $b = $a; Copy reference ($a) = ($b) ={id1} $a->bar = 2;echo "B->bar = $b->bar\n"; $b->bar = 3;echo "A->bar = $a->bar\n";//Modified B, but actually modifies the same object referenced by A and b//and does not throw a Copy on Write to create a new object b$a = new Foo; $a was modified to a new reference, $b did not change //($a) ={id2} ($b) ={id1} $a->bar = 4;echo "B->bar = $b->bar\n"; $b = & $a; To explicitly use a reference, B becomes a reference to "object" $ A = new Foo; ($a) ={id3} ($b) =& ($a) =&{id3} $a->bar = 5;echo "B->bar = $b->bar\n"//==output====b->bar = 2a-> Bar = 3b->bar = 3b->bar = 5
http://www.bkjia.com/PHPjc/952700.html www.bkjia.com true http://www.bkjia.com/PHPjc/952700.html techarticle PHP variable Reference (nbsp;1) reference to PHP reference two variables pointer to the same memory address $a =abc; $b = $a; echo $a;//output here: Abcecho $b;//output here: Abc$b=efg;echo $a;