Explanation below: What $a=test(); gets in this way is not actually a reference return of the function. It is no different from an ordinary function call. The reason: This is the regulation of PHP PHP stipulates that $a=&test (); method is the reference return of the function As for what is a reference return (the PHP manual says: reference return is used when you want to use a function to find which variable the reference should be bound to.) This is bullshit I couldn’t understand it for a long time
Using the above example to explain, calling a function using $a=test() only assigns the value of the function to $a, and any changes to $a will not affect $b in the function and through $ When calling a function in the a=&test() method, its function is to point the memory address of the $b variable in return $b and the memory address of the $a variable to the same place , which produces the equivalent of this effect ($a =&b;) So changing the value of $a also changes the value of $b, so after executing
- 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 will output the value of $b as 2
-
- $a=&test( );//This statement will output the value of $b as 3
- $a=5;
- $a=test();//This statement will output the value of $b as 6
Copy code
- /* Here’s another little episode
- The pointing (similar to pointer) function of the address in PHP is not implemented by the user himself, but is implemented by the Zend core. The reference in PHP uses "copy-on-write" The principle is that unless a write operation occurs, variables or objects pointing to the same address will not be copied.
-
- In layman terms
- 1: If you have the following code
- */
- $a="ABC";
- $b=$a;
- /*
- In fact, $a and $b both point to the same memory address at this time. It’s not that $a and $b occupy different memories
-
- 2: If you add the following code to the above code
- */
- $a="EFG";
- /*
- Because $a and $b point to The data in the memory needs to be written again. At this time, the Zend core will automatically determine and automatically produce a data copy of $a for $b, and re-apply for a piece of memory for storage*/
Copy code
|