PHP variable reference (& amp;), function reference, and object reference. PHP variable reference (nbsp; 1. variable reference PHP references the pointer of two variables pointing to the same memory address $ aABC; $ B $ a; echo $ a; output: ABCecho $ B; output: ABC $ bEFG; echo $ a; PHP variable reference (&), function reference, and object reference
1. variable reference
PHP references the pointer of two variables to the same memory address
$ A = "ABC"; $ B = & $ a; echo $ a; // output here: ABCecho $ B; // output here: ABC $ B = "EFG "; echo $ a; // Here, the value of $ a is changed to EFG, so EFGecho $ B is output. // Here, EFG is output.
2. function reference transfer (address transfer)
Function test (& $ a) {$ a = $ a + 100;} $ B = 1; echo $ B; // output 1 test ($ B ); // Here $ B is actually the memory address of the variable content of $ B. by changing the value of $ a in the function, you can change the value of $ B. echo"
"; Echo $ B; // output 101?>
3. function reference return
Function & test () {static $ B = 0; // declare a static variable $ B = $ B + 1; echo $ B; return $ B ;} $ a = test (); // This statement will output the value of $ B as 1 $ a = 5; $ a = test (); // This statement outputs the value of $ B as 2 $ a = & test (); // This statement outputs the value of $ B as 3 $ a = 5; $ a = test (); // This statement outputs a value of 6 for $ B.
The following explains:
In this way, $ a = test (); is not actually returned by the function reference, which is no different from the normal function call. The reason is: this is the php rule.
When calling a function using $ a = & test (), the function directs the memory address of the $ B variable in return $ B to the same place as the memory address of the $ a variable.
That is, the equivalent effect ($ a = & $ B;) is generated. Therefore, changing the value of $ a also changes the value of $ B.
4. object reference (PHP5)
Class foo {public $ bar = 1 ;}$ a = new foo; // $ a is actually a reference $ B = $ a; // Copy reference ($) = ($ B) = {id1} $ a-> bar = 2; echo "B-> bar = $ B-> bar \ n "; $ B-> bar = 3; echo "a-> bar = $ a-> bar \ n"; // Modified B, but it actually modifies the same object referenced by a and B. // it does not trigger Copy On Write to create a new object B $ a = new foo; // $ a is changed to a new reference, and $ B is not changed // ($ a) = {id2} ($ B) = {id1} $ a-> bar = 4; echo "B-> bar = $ B-> bar \ n"; $ B = & $; // use the reference explicitly. B becomes the reference of "object reference" $ 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
Signature (nbsp; 1. variable reference PHP references the pointer of two variables pointing to the same memory address $ a = ABC; $ B = $ a; echo $ a; // output here: ABCecho $ B; // output here: ABC $ B = EFG; echo $ ;...