Php reference (&)

Source: Internet
Author: User
PHP references (that is, adding the & amp; symbol before variables, functions, objects, or object methods & nbsp;) in PHP mean: different names access the content of the same variable. The pointer is different from the pointer in C language. The pointer in the C language stores the variable content and the address stored in the memory. 1. the reference of the variable PHP allows you to use two variables to point to the same content. & Lt ;? Php $ a & quot; ABC & quot; $ B & amp; $ a; echo $; here, the PHP reference (that is, adding an & symbol before a variable, function, object, or object method) in PHP means that different names access the same variable content.

The pointer is different from the pointer in C language. The pointer in the C language stores the variable content and the address stored in the memory.

1. variable reference

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

 $ A = "ABC ";
$ B = & $;
Echo $ a; // output here: ABC
Echo $ B; // output here: ABC
$ B = "EFG ";
Echo $ a; // Here, the value of $ a is changed to EFG, So EFG is output.
Echo $ B; // output EFG here

?>

2. Function Reference

I will not talk about the transfer (transfer address call) transfer address call. the following code is provided:

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

?>

Note that test (1); will cause an error. Note: Do not add the & symbol before $ B in the above "test ($ B);", but in the function "call_user_func_array", to reference the parameter passing, the & symbol is required, as shown in the following code:

 Function a (& $ B ){
$ B ++;
}
$ C = 0;
Call_user_func_array ('A', array (& $ c ));
Echo $ c; // output 1

?>

3. function reference return

First look at the code:

 Function & test (){
Static $ B = 0; // declare a static variable
$ B = $ B + 1;
Echo $ B;
Return $ B;
}

$ A = test (); // This statement outputs the value of $ B as 1.
$ A = 5;
$ A = test (); // This statement outputs the value of $ B to 2.

$ A = & test (); // This statement outputs the value of $ B to 3.
$ A = 5;
$ A = test (); // This statement outputs a value of 6 for $ B.

?>

The following explains:

In this way, $ a = test (); is not actually returned by the function reference, which is no different from the normal function call. As for the reason:

This is what PHP requires. PHP requires the $ a = & test (); method to obtain the function reference and return. what is the reference return? (the PHP manual says: the return value of the reference is used when you want to use the function to find the variable on which the reference should be bound .)

The preceding example shows that $ a = test () is used to call a function, but the function value is assigned to $ a, and $ a makes any changes, does not affect $ B in the function, but calls the function in the $ a = & test () method, it directs the memory address of the $ B variable in return $ B to the same place as the memory address of the $ a variable, that is, the equivalent effect ($ a = & $ B;) is generated. Therefore, changing the value of $ a also changes the value of $ B, therefore, $ a = & test ();

$ A = 5; then, the value of $ B is changed to 5. Static variables are used to help you understand the reference and return functions. In fact, function reference and return are mostly used in objects.

Another official PHP example is provided:

 // This is the way how we use 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 = 'Are';
$aa->out();
$d = 'You';
$aa->out();

// the output is "HiHowAreYou"

?>

4. object reference

 Class {
Var $ abc = "ABC ";
}
$ B = new;
$ 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 running effect in PHP5. In PHP5, object assignment is a reference process. In the above column, $ B = new a; $ c = $ B; is equivalent to $ B = new a; $ c = & $ B ;, in PHP5, the object is called by reference by default, but sometimes you may want to create a copy of the object and expect that the change of the original object will not affect the copy.

For this purpose, PHP5 defines a special method called _ clone. Since PHP 5, new automatically returns a reference. Therefore, when = & is used here, messages at the E_STRICT level will be generated.

In PHP4, an object value assignment is a copy process, for example, $ B = new a. new a generates an anonymous a object instance, in this case, $ B copies the anonymous object. Similarly, $ c = $ B is a copy of $ B content. Therefore, in PHP4, to save memory space, $ B = new a is generally changed to the reference mode, that is, $ B = & new.

5. Role of reference

If the program is large, there are many variables that reference the same object, and you want to manually clear the object after it is used up, I suggest using the & method, then, clear it in the form of $ var = null. In other cases, use the default PHP5 method. In addition, we recommend that you use the "&" method for transferring large arrays in PHP5 to save memory space.

6. cancel the reference.

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

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

Not unset $ B, just $. 7. global reference when a variable is declared using global $ var, a reference to the global variable is actually created. That is to say, it is the same as doing so:

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

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

Example reference global variables in a function

 $var1 = "Example variable";
$var2 = "";

function global_references($use_globals) {
global $var1, $var2;
if (!$use_globals) {
$var2 = &$var1; // visible only inside the function
} else {
$GLOBALS["var2"] = &$var1; // visible also in global context
}
}

global_references(false);
echo "var2 is set to '$var2'
"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'
"; // var2 is set to 'Example variable'
?>

Use global $ var as the abbreviation of $ var = & $ GLOBALS ['var.

Therefore, assigning other references to $ var only changes the reference of local variables. 8. $ this in an object method, $ this is always a reference to the object that calls it. // In the next episode, the point-to-address (similar to pointer) function in PHP is not implemented by the user, but by the Zend core, the reference in PHP adopts the principle of "copy at Write Time", that is, unless a write operation occurs, the variables or objects pointing to the same address will not be copied. In layman's terms

1. if the following code exists:

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

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

2. add the following code on the basis of the above code:

 $a = "EFG";
?>

Because the memory data pointed to by $ a and $ B needs to be re-written, the Zend core will automatically determine and automatically generate a $ a data copy for $ B, applying for a new memory to store PHP references (that is, adding & symbol before variables, functions, and objects) is a high-level topic, correct understanding of PHP references is very important and has a great impact on performance, and understanding errors may lead to program errors! 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 to be explicitly declared in the array transfer process, but must be fixed using *. in PHP, pointers to addresses (similar to pointers) the function is not implemented by the user, but by the Zend core. the reference in PHP adopts 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, $ a 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 parameters by referencing, and print the output array size.

Function printArray (& $ arr) {// reference transfer
Print (count ($ arr ));
}
PrintArray ($ );

In the above code, we pass the $ a array into the printArray () function through reference. 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 the reference will lead to a performance reduction of more than 30%.

Self-understanding: values are irrelevant to parameters in the function, which is equivalent to local variables, while values are related to parameters in the function by reference, it is equivalent to a global variable. In terms of performance, the above analysis is sufficient.

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.