Php reference (&) explanation and precautions _ PHP Tutorial

Source: Internet
Author: User
Tags php example
Php reference (& amp;) details and precautions. Php reference (amp; symbol) 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 is stored in the variable php reference (&) details and precautions

PHP reference (that is, add the & symbol before a variable, function, object, or object method)

The reference 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.

 

2. functionReference transfer(Address Transfer call)

I won't say much about the address transfer call. the code is provided below:

 "; Echo $ B; // output 101?>

Note that test (1); will cause an error.

Note:

In the above "test ($ B);", do not add the & symbol before $ B, but in the function "call_user_func_array", to reference the parameter passing, you need the & symbol, the following code is used:

 

3. functionReference return

First look at the code:

 

The following explains:

In this way, $ a = test (); does not actually get the function reference and return, which is no different from the normal function call. The reason is: this is the PHP rule.

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 .) I haven't understood this sentence for a long time.

The example above is as follows:

$ A = test () is used to call a function. it only assigns the value of the function to $ a. any change made to $ a does not affect $ B in the function, but how to call a function through $ a = & test, it directs the memory address of the $ B variable in return $ B to the same place as the memory address of the $ a variable, this is equivalent to the effect ($ a = & $ B;). Therefore, changing the value of $ a also changes the value of $ B.

$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:

 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

 Abc; // output ABCecho $ c-> abc here; // output ABC $ 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.

The following is an official example:

In PHP5, you can get the "object reference" function without adding anything else:

 name = $str;}function __toString() {return 'my name is "' . $this->name . '" and I live in "' . __CLASS__ . '".' . " ";}function setName($str) {$this->name = $str;}}class MasterOne {protected $foo;function __construct($f) {$this->foo = $f;}function __toString() {return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . " ";}function setFooName($str) {$this->foo->setName($str);}}class MasterTwo {protected $foo;function __construct($f) {$this->foo = $f;}function __toString() {return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . " ";}function setFooName($str) {$this->foo->setName($str);}}$bar = new foo('bar');print(" ");print("Only Created $bar and printing $bar ");print($bar);print(" ");print("Now $baz is referenced to $bar and printing $bar and $baz ");$baz = &$bar;print($bar);print(" ");print("Now Creating MasterOne and Two and passing $bar to both constructors");$m1 = new MasterOne($bar);$m2 = new MasterTwo($bar);print($m1);print($m2);print(" ");print("Now changing value of $bar and printing $bar and $baz");$bar->setName('baz');print($bar);print($baz);print(" ");print("Now printing again MasterOne and Two");print($m1);print($m2);print(" ");print("Now changing MasterTwo's foo name and printing again MasterOne and Two");$m2->setFooName('MasterTwo\'s Foo');print($m1);print($m2);print("Also printing $bar and $baz");print($bar);print($baz);?>

Output:

Only Created $ bar and printing $ bar
My name is "bar" and I live in "foo". Now $ baz is referenced to $ bar and printing $ bar and $ baz
My name is "bar" and I live in "foo". Now Creating MasterOne and Two and passing $ bar to both constructors
Master: MasterOne | foo: my name is "bar" and I live in "foo ". master: MasterTwo | foo: my name is "bar" and I live in "foo ". now changing value of $ bar and printing $ bar and $ baz
My name is "baz" and I live in "foo ".
My name is "baz" and I live in "foo". Now printing again MasterOne and Two
Master: MasterOne | foo: my name is "baz" and I live in "foo ". master: MasterTwo | foo: my name is "baz" and I live in "foo ". now changing MasterTwo's foo name and printing again MasterOne and Two
Master: MasterOne | foo: my name is "MasterTwo's Foo" and I live in "foo ". master: MasterTwo | foo: my name is "MasterTwo's Foo" and I live in "foo ". also printing $ bar and $ baz
My name is "MasterTwo's Foo" and I live in "foo ".
My name is "MasterTwo's Foo" and I live in "foo ".

Analysis of the previous example:

$bar = new foo('bar');$m1 = new MasterOne($bar);

The $ bar in the instance object $ m1 and $ m2 is a reference to the instance $ bar instead of a copy. this is a feature of object reference in PHP5, that is

  1. Inside $ m1 or $ m2, any operation on $ bar will affect the value of $ bar of the external object instance.
  2. The change of the external object instance $ bar also affects the reference values of $ m1 and $ m2.

In PHP4, the equivalent code (that is, reference and call) is similar to the preceding example when an object instance is used as an attribute of another object:

class foo{var $bar;function setBar(&$newBar) {$this->bar = $newBar;}}

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:

 

Not unset $ B, just $.

7. global reference

When a variable is declared with global $ var, a reference to the global variable is actually created. That is to say, it is the same as doing so:

 

This means that, for example, unset $ var does not unset global variables.

If a function is declaredGlobalThe variable is assigned to a reference, which is only visible within the function. You can use$ GLOBALSArray to avoid this.

Example reference global variables in a function

 

SetGlobal $ var;As Yes$ Var = & $ GLOBALS ['var'];. To assign other references$ VarOnly the reference of local variables is changed.

8. $ this

In the method of an object, $ this is always a reference to the object that calls it.

// Next is an episode

In PHP, the address pointing (similar to pointer) function is not implemented by the user, but is implemented by the Zend core. in PHP, the reference uses the principle of "copy at Write, 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:

 

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:

 

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) {// Pass print (count ($ arr) by referencing;} 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) {// 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.

Articles you may be interested in
  • Php Security programming considerations
  • In php, we use the curl post method to submit data and the get method to obtain webpage data.
  • Note the use of return in php recursive functions
  • Website Space Security considerations
  • ThinkPHP built-in template engine usage summary
  • Php uses array_flip to implement array key-value exchange to remove array duplicate values
  • Php uses regular expressions to filter various tags, spaces, and line breaks.
  • PHP implements MVC development in the simplest way, model thinking

The signature (amp; symbol) referenced in PHP means that different names access the same variable content. The pointer is different from the pointer in C language. The pointer in C language stores the variable...

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.