Many people misunderstand that the reference in php is the same as the pointer in C. In fact, this is not the case and it is quite different. In C language, pointers do not need explicit declarations in addition to the array transfer process, but must be defined by *. in php, pointers to addresses (similar to pointers) functions are not implemented by the user, but are implemented by the Zend core. PHP references and symbols use the principle of "Copy at write time", that is, unless a write operation occurs, variables or objects pointing to the same address are not copied, for example, the following code:
- $a = array('a','c'...'n');
- $b = $a;
If the program is only executed here, $ B and $ B are the same, but not like C, $ a and $ B occupy different memory space, it points to the same memory, which is the difference between php and c. It does not need to be written as $ B = & $ a to indicate that $ B points to $ a memory, zend has already helped you implement the reference, and zend will be very intelligent to help you determine when to handle this and when not.
If you continue to write the following code later, add a function, pass the parameter through PHP Reference & symbol, and print the output array size.
- Function printArray (& $ arr) // reference Transfer
- {
- Print (count ($ arr ));
- }
-
- PrintArray ($ );
In the above Code, we use PHP Reference & symbol to pass the $ a array into the printArray () function. The zend engine will think that printArray () may cause changes to $, at this time, a $ a data copy is automatically generated for $ B, and a memory is re-applied for storage. This is the "Copy at write time" concept mentioned above.
If we change the above Code to the following:
- Function printArray ($ arr) // value transfer
- {
- Print (count ($ arr ));
- }
-
- PrintArray ($ );
The above Code directly transmits the $ a value to printArray (). At this time, there is no reference transfer, so there is no copy at write time.
You can test the execution efficiency of the above two lines of code, for example, adding a loop 1000 times outside to check the running time, the result will let you know that improper use of PHP references and symbols will lead to a performance reduction of more than 30%.