PHP references (&) details and considerations

Source: Internet
Author: User
A reference to PHP (that is, a variable or function or object or object method preceded by A & symbol) is referenced in PHP to mean that different names access the same variable content.

There is a difference between the pointers in the C language. The pointer inside the C language stores the contents of the variable, storing the address in memory.

1. References to variables

PHP references allow you to use two variables to point to the same content.

  
   
$a = "ABC";
$b = & $a;
echo $a; Output here: ABC
Echo $b; Output here: ABC
$b = "EFG";
echo $a; Here a $ A value becomes EFG so the output EFG
Echo $b; Output EFG Here

?>

2. References to functions

Pass (address call) address call I don't say much, the following code is given directly:

  
   
Function test (& $a) {
$a = $a + 100;
}
$b = 1;
Echo $b; Output 1
Test ($b); Here $b passed to the function is actually the memory address of the variable content of $b, by changing the value of $ A in the function, you can change the value of $b.
echo "
";
Echo $b; Output 101

?>

Note that the test (1) is here; The words will go wrong, cause to think for yourself. Note: The above "Test" ($b); Do not add the & symbol in front of the $b, but in the function "Call_user_func_array", to reference the arguments, you need the & symbol, as shown in the following code:

  
   
Function A (& $b) {
$b + +;
}
$c = 0;
Call_user_func_array (' A ', Array (& $c));
Echo $c; Output 1

?>

3. A reference to a function returns

Look at the code first:

  
   
function &test () {
Static $b = 0;//declares a static variable
$b = $b + 1;
Echo $b;
return $b;
}

$a = Test (); This statement will output a value of 1 for the $b
$a = 5;
$a = Test (); This statement will output a value of 2 for the $b

$a = &test (); This statement will output a value of 3 for the $b
$a = 5;
$a = Test (); This statement will output a value of 6 for the $b

?>

The following explanation:

In this way $a =test (); The result is not a function reference return, which is no different from the normal function call, as for the reason:

This is the PHP rule. PHP rules through $a=&test (); The way to get the function is to return the reference, as to what is a reference to return it (the PHP manual says: Reference return is used when you want to use a function to find the reference should be bound to the top of the variable.) )

This is explained by the above example: $a = Test () Call the function, just assign the value of the function to $ A, and no change to $ A will not affect the $b in the function, but by $a = &test () Call the function, it is the function of return $b in the $ The memory address of the B variable and the memory address of the $ A variable are all pointing to the same place, which produces the equivalent effect ($a = & $b;) So changing the value of $ A also changes the value of $b, so it executes a $ A = &test ();

$a = 5; Later, the value of $b becomes 5. This is to let everyone understand that the function reference returns only use static variables, in fact, the function of the reference return is used in the object.

Also attached is a PHP official example:

  
   
This is the the-the-pointer to access variable inside the class.
Class talker{

Private $data = ' Hi ';

Public Function & get () {
return $this->data;
}

Public function out () {
Echo $this->data;
}
}

$AA = new talker ();
$d = & $aa->get ();

$aa->out ();
$d = ' how ';
$aa->out ();
$d = ' is ';
$aa->out ();
$d = ' you ';
$aa->out ();

The output is "hihowareyou"

?>

4. References to Objects

 
  Class A {
var $abc = "abc";
}
$b = new A;
$c = $b;
Echo $b->abc; Output ABC here
Echo $c->abc; Output ABC here
$b->abc= "DEF";
Echo $c->abc; Output DEF here

?>

The above code is the result of running in PHP5. The assignment of an object in PHP5 is a reference procedure. The above $b = new A; $c = $b; is actually equivalent to $b = new A; $c = & $b, the default in PHP5 is to invoke the object by reference, but sometimes you might want to make a copy of an object, and you want the original object to change without affecting the copy.

For this purpose, PHP5 defines a special method called __clone. Since PHP 5, new automatically returns references, so using =& here is obsolete and generates E_STRICT-level messages.

In PHP4, the assignment of an object is a copy process, such as: $b = new A, where new a produces an anonymous instance of a object, at which point the $b is a copy of the anonymous object. The same $c = $b, also a copy of the $b content. So in PHP4, in order to save memory space, $b = new A is generally changed to the referenced pattern, that is $b = &new A.

5. Role of references

If the program is larger, the variable that references the same object is more, and you want to clear it manually after the object is exhausted, the personal suggestion is "&" and then clear it with $var = null. At other times, it's the default way to use PHP5. In addition, in the PHP5 for large arrays of delivery, it is recommended to use "&" mode, after all, saving memory space to use.

6. dereference

When you unset a reference, you just break the binding between the variable name and the variable content. This does not mean that the contents of the variable are destroyed. For example:

 
  $a = 1;
$b = & $a;
unset ($a);
?>

Not unset $b, just $a. 7.global references When you declare a variable with the global $var, you actually establish a reference to a global variable. In other words, it is the same as doing this:

 
  $var = & $GLOBALS ["var"];
?>

This means, for example, that the unset $var does not unset global variables. If a variable declared as global is assigned to a reference within a function, the reference is only visible inside the function. You can avoid this by using an array of $GLOBALS.

Example referencing global variables within a function

 
  $var 1 = "Example variable";
$var 2 = "";

function global_references ($use _globals) {
Global $var 1, $var 2;
if (! $use _globals) {
$var 2 = & $var 1; Visible only inside the function
} else {
$GLOBALS ["var2"] = & $var 1; Visible also in global context
}
}

Global_references (FALSE);
echo "VAR2 is set to ' $var 2 '
"; VAR2 is set to '
Global_references (TRUE);
echo "VAR2 is set to ' $var 2 '
"; VAR2 is set to ' Example variable '
?>

$var the global; As $var = & $GLOBALS [' var ']; The shorthand.

Thus assigning other references to $var only changes the reference to the local variable. 8. $this in the method of an object, $this is always a reference to the object that invokes it. Here's another episode. The pointer to the address in PHP (similar to pointers) is not implemented by the user themselves, is implemented by the Zend Core, PHP refers to the use of "copy-on-write" principle, that is, unless a write operation, a pointer to the same address of the variable or object will not be copied. The popular Speaking

1, if you have the following code

 
  $a = "ABC";
$b = & $a;
?>

In fact, $a and $b both point to the same memory address and not $ A and $b occupy different memory

2, if the above code based on add the following code

 
  $a = "EFG";
?>

Since $ A and $b point to the memory of the data to be re-written once, at this time Zend core will automatically determine, automatically for $b production of a $ A copy of the data, re-request a piece of memory to store PHP reference (that is, variables or functions, objects, etc. before adding & symbols) is a high-level topic, Novice more attention, the correct understanding of PHP reference is very important, the performance has a large impact, and understanding errors can lead to program errors! Many people misunderstand that the reference in PHP is the same as the pointer in C, which is not, in fact, very different.

In addition to the pointer in the C language is not explicitly stated in the process of the array, the others need to be defined using *, and PHP's point-of-address (similar pointer) function is not implemented by the user itself, is implemented by the Zend Core, PHP reference in the use of "copy-on-write" principle, Unless a write operation occurs, a variable or object that points to the same address is not copied, such as the following code: $a = Array (' A ', ' C ' ... ' n ');
$b = $a; If the program only executes here, $a and $b are the same, but not like C, $a and $b occupy different memory space, but instead point to the same piece of memory, which is the difference between PHP and C, do not need to write $b=& $a to represent the $b point to $ A memory, Zend has already helped you to make references, and Zend will be very intelligent to help you decide when to deal with this and when not to do so. If you continue to write the following code, add a function, pass the parameter by reference, and print the output array size.

Function PrintArray (& $arr) {//reference Pass
Print (count ($arr));
}
PrintArray ($a);

In the above code, we pass the $ A array into the PrintArray () function by reference, and the Zend engine will think that PrintArray () may cause a change to $ A, which will automatically produce a $ A copy of the data for $b and re-request a piece of memory for storage. This is the "copy-on-write" concept mentioned earlier. If we change the code above to the following:

function PrintArray ($arr) {//value Pass
Print (count ($arr));
}
PrintArray ($a);

The above code passes a $ A value directly into PrintArray () and there is no reference pass at this time, so there is no write-time copy.

You can test the execution efficiency of the two lines of code above, such as adding a loop 1000 times outside to see how time is running, and the result will let you know that incorrect use of the reference will result in a decrease in performance by more than 30%.

Self-understanding: According to the value of the word is independent of the parameters within the function, equivalent to the role of local variables, and according to the address (reference) is related to the parameters within the function, equivalent to the role of global variables. In terms of performance, look at the above analysis is enough.

  • 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.