1. References to variables
PHP refers to a two-variable pointer to the same memory address
$a = "ABC";
$b =& $a;
echo $a//Here output: ABC
echo $b//Here output: ABC
$b = "EFG";
echo $a//Here the value of $a becomes EFG so output EFG
echo $b;//Here Output EFG
2. Reference Pass of function (call to address)
Function test (& $a)
{
$a = $a +100;
}
$b =1;
echo $b//Output 1
test ($b); Here $b passed to the function is actually the $b variable content of the memory address, by changing the value of $a in the function can change the value of the $b
echo "<br>";
echo $b;/output
?>
3. The reference of the 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 outputs $b value of 2
$a =&test ();//This statement outputs $b value of 3
$a =5;
$a =test ()//This statement will output $b value of 6
The following explains:
$a=test in this way (); What you get is not the return of a reference to a function, which is no different from a normal function call. As for the reason: this is the PHP rule
Calling a function by $a=&test () means that the memory address of the $b variable in the return $b is directed to the same place as the memory address of the $a variable.
That produces the equivalent effect ($a =& $b;) So changing the value of the $a also changes the value of the $b, so in the execution of 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->barn";
$b->bar = 3;
echo "A->bar = $a->barn"; Modified B, but it actually modifies the same object referenced by A and B, and does not raise Copy on Write to create a new object b $a = novel Foo;
$a was modified to a new reference, $b not changed//($a) ={id2} ($b) ={id1} $a->bar = 4;
echo "B->bar = $b->barn"; $b = & $a; Using the reference explicitly, B becomes a reference to the "object reference" $a = new Foo;
($a) ={id3} ($b) =& ($a) =&{id3} $a->bar = 5; echo "B->bar = $b->barn"//==output==== B->bar = 2 A->bar = 3 B->bar = 3 B->bar = 5