- $ A = array (1, 4, 5 );
- $ B = $ a; // The array is not copied.
- $ A [1] = 10; // The array is copied and the value is modified.
- Print_r ($ );
- Print_r ($ B );
- ?>
-
After running, the values of $ a and $ B are different. $ A is, 5 $ B is, 5, which is a bit similar to the value assignment of the C # value type. To make $ a and $ B always be the same reference, write the code as follows:
- $ B = & $;
-
A term used in PHP to match the Copy-on-write technology is referred to as reference count ). In PHP, each variable is composed of two parts: a variable name and a variable value. they are stored in a structure called a symbol table, which is an array, it maps the location of the variable name and value in the memory. Each value in the symbol table has a so-called reference count, which records how many methods can be used to obtain this value, that is, how many variable names point to this value. In the above code, after $ a is initialized, after $ B = $ a, this array has a reference count 2 (if you view the reference count through the C API method, this value is actually 3, but from the user's point of view, it can be better understood as 2 ). The value in the memory can be obtained in two ways, through $ a and $ B. then, when the value of $ a [1] is changed, php creates a new memory space for $ a, that is, two arrays. The reference count of both arrays is 1. When a variable out of the scope, such as a local variable in the function, the variable becomes invalid after the function is run, the reference count of the value pointed to by this variable is reduced by 1. Similarly, if a variable points to a new memory address, the reference count on the value of this old address will be reduced by 1. When the reference count of a memory space is 0, it will be released by PHP. |