An explanation of PHP references

WBOY
Release: 2016-07-25 08:56:14
Original
1096 people have browsed it
  1. function &bar() {
  2. $a = 5;
  3. return $a;
  4. }
Copy the code

when used as follows: $ret = &bar(); That is, the ampersand must be added when defining and using it.

5, assignment and transfer of objects Note: There is a difference in the assignment and passing of object resources in PHP4 and PHP5. In PHP4:

  1. $a = new Object() In fact, $a and new Object() are mapped to different object instances, so $a = & new Object() needs to be explicitly used for reference assignment transfer.
  2. $b = $a Same as above.
  3. foo(new Object()) / foo($a) Same as above.
  4. foo() {$a = new Object(); return $a} Same as above.
Copy code

PHP5:

  1. $a = new Object() Both map to the same object and do not need to use reference characters.
  2. $b = $a Same as above.
  3. foo(new Object()) / foo($a) Same as above.
  4. foo() {$a = new Object(); return $a} Same as above.
Copy code

Remarks: Found during testing: After $a = new Object(); $b = $a, if $a->attr = 12; $b->attr = 13, the final result is that both $a->attr and $b->attr are equal to 13, Rather than being independent as imagined. It may be that $a->attr and $b->attr are not deeply copied, but are still different mappings of the same memory. If $a = new Object(); $b = &$a;, there is no such doubt, because there is only one real object from beginning to end, and $a and $b are just mappings.

6, unset and =null The results of using unset($a) and $a=null are different. If this block of memory only has one mapping of $a, then unset($a) is equivalent to $a=null, and the reference count of the memory becomes 0 and is automatically recycled; If the block of memory has two mappings of $a and $b, then unset($a) will cause $a=null and $b remains unchanged, and $a=null will cause $a=$b=null. .

Cause analysis: Assigning a variable to null will cause the reference count of the memory block corresponding to the variable to be directly set to 0 and automatically recycled.



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!