Careful use of PHP reference types

Source: Internet
Author: User
The Reference type is used in many computer languages and exists as a very powerful and practical feature. it has implementations similar to pointers, but it is different from pointer

The Reference type is used in many computer languages and exists as a very powerful and practical feature. it has implementations similar to pointers, but it is different from the pointer.

For example, the reference of C ++ allows different variables to point to the same object, while also directly using dot to obtain object members, without the tedious use of the dereference operator (*) and the Pointer to Member operator (->), Java and C # are directly referenced as the main type, and developers should try to avoid using pointers.

The reference type is also introduced in PHP. in the transfer of value assignment to an object, it can basically be considered as a reference transfer equivalent to Java/C # (for details, see Objects and references ), at the same time, the reference of content can be obtained through the reference operator (&) on the basic type. However, in actual use, the reference type of PHP has many problems due to the entire PHP design structure, causing unexpected results in the program.

The referenced variable can be assigned a new reference.

In C ++, a variable of the reference type can only be assigned a reference value when it is defined. Therefore, we only need to track the definition of the variable to know which content the variable is operating on.

Different from PHP, the definition of variables is blurred in PHP, and variables can be used without definition. Therefore, you can assign reference values to variables multiple times. The code is as follows:

$ X = 21; $ y = 7; $ z = & $ x; $ z = & $ y;

Var_dump ($ x, $ y, $ z); for the first time, it seems that $ z is a reference to $ x, then, the content of $ z is changed to a reference to $ y, that is, $ x and $ z are both references to $ y, but the actual output result is:

Int (21), int (7), int (7)

The result shows that $ x remains unchanged, but $ z is changed to a reference to $ y, which is equivalent to unsetting the $ z variable and then assigning a new value.

$ Z = & $ x; unset ($ z );

$ Z = & $ y; this is actually a reasonable logic. for example, the following code does not get a Pointer similar to a Pointer) "Reference refer to a Referenece" is just a Reference variable that references the same content.

$ X = 21; $ y = & $ x; $ z = & $ y

Referencing an array element changes the element to a reference type. retrieving a reference to a variable does not change the original variable type. However, if the element in the array is used, however, this element will also become a reference type.

Before reading the problematic code, we should first point out that the PHP array assignment is copy rather than reference. the assignment process will create a new array and assign it to the assigned variable, the array operation on the new variable does not affect the content of the original array variable. the code is as follows:

  1. $ A = array (21, 7 );
  2. $ B = $;
  3. $ B [0] = 7;
  4. Var_dump ($ );
  5. Echo'
    ';
  6. Var_dump ($ B );
  7. // Output:
  8. // Array (2) {[0] => int (21) [1] => int (7 )}
  9. // Array (2) {[0] => int (7) [1] => int (7 )}

Next let's take a look at the exception if the element in the array is referenced.

  1. $ A = array (21, 7 );
  2. $ C = & $ a [0];
  3. $ B = $;
  4. $ B [0] = "21 ";
  5. $ B [1] = "7 ";
  6. Var_dump ($ );
  7. Echo'
    ';
  8. Var_dump ($ B );
  9. Echo'
    ';
  10. Var_dump ($ c );
  11. Echo'
    ';
  12. // Output:
  13. // Array (2) {[0] => & string (2) "21" [1] => int (7 )}
  14. // Array (2) {[0] => & string (2) "21" [1] => string (1) "7 "}
  15. // String (2) "21"

In the code, $ B is just a simple assignment, but a reference to the first element is added, but a new array is copied. However, the result is a change to $ B, and the first element of $ a is also changed, but the second element has no effect.

From the output, we also see an unusual place, that is, the type of the first element of the array is an extra '&' symbol. This is the reference operator. That is to say, the first element of the array has become the reference type. Therefore, when values are assigned, copying is also referenced, rather than copying values.

This problem is very strange, and it also caused a lot of unnecessary troubles in development. I thought the copied array was not associated with the original array, but it was because of the unexpected reference type, it also affected the original array during operation.

I do not know whether this is a bug in PHP, but I still intend to design it like this. I haven't explained this convenience for a long time on the internet. only the "PHP: references To Array Elements Are Risky, which is mentioned in Problems w/accessing a PHP array by reference in wide Ric Designs, but there is no reason for this.

Several related reports (Bug6417, Bug7412, Bug15025, and Bug20993) are displayed in the PHP Bug Report ). Some say this is a Bug and it has been fixed in later versions. I do not understand the details. I can only avoid using references on arrays.

What's more interesting is that if unset references are left with only one element, the array element will become a normal type without reference. the code is as follows:

  1. Unset ($ B );
  2. Unset ($ c );
  3. Var_dump ($ );
  4. // Output:
  5. // Array (2) {[0] => string (2) "21" [1] => int (7 )}

Avoid using PHP references

In fact, this is the point of attention mentioned in PHP Array Manual. it occurs most often in foreach, and you want to change the value of the far Array through reference (see this article ).

In fact, I want to use foreach with reference to change the value of the Array element, mainly because the PHP Array is an Associative Array, which can be an Array of "undefined length, index can be discontinuous, strings and integers can be used as indexes at the same time, so we cannot use the for loop to simply add an integer index.

Of course, we can directly change the value of the array element through $ key as in the code below, but this may have some efficiency problems. The code is as follows:

  1. Foreach ($ array_var as $ key => $ value)
  2. $ Array_var [$ key] = $ newValue;

Another common reference is to use references to pass parameters in function calls. The main reason is that you want the function to return multiple return values through this method, for example, we want to use a representation to indicate whether the function has an error during execution and the returned value is invalid.

However, because PHP functions can return different types, you do not need to input reference parameters for representation. even if multiple return values are required, you can also return the "array with string as the primary key" as the solution, but you may need to indicate in the document that each element corresponds to that result.

There is a better way to operate, it should be that whenever the referenced variable no longer needs to be used, it will immediately use unset for the variable to switch between it and the content. And even if the variable is not of the reference type, we confirm that it is no longer used and there is no problem in calling unset for it. At least make sure that the previous result is not affected when the variable is assigned again later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.