php reference

WBOY
Release: 2016-07-25 09:09:17
Original
938 people have browsed it

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

  1. function &test()
  2. {
  3. static $b=0;//Declare a static variable
  4. $b=$b+1;
  5. echo $b;
  6. return $b;
  7. }
  8. $a=test ();//This statement will output the value of $b as 1
  9. $a=5;
  10. $a=test();//This statement will output the value of $b as 2
  11. $a=&test( );//This statement will output the value of $b as 3
  12. $a=5;
  13. $a=test();//This statement will output the value of $b as 6
Copy code
  1. /* Here’s another little episode
  2. 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.
  3. In layman terms
  4. 1: If you have the following code
  5. */
  6. $a="ABC";
  7. $b=$a;
  8. /*
  9. 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
  10. 2: If you add the following code to the above code
  11. */
  12. $a="EFG";
  13. /*
  14. 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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!