PHP Reference (&) Examples of various use methods

Source: Internet
Author: User
Tags anonymous php class php and zend

 php reference (that is, precede a variable or function, object, and so on & symbol), referenced in PHP means: different names to access the same variable content. There is a difference between the pointers in the C language. In the C language, the pointer stores the contents of the variable, and the address that is stored in memory

PHP references (in addition to the variables or functions, objects, etc. before the & symbol), in PHP refers to the meaning: different names to access the same variable content. There is a difference between the pointers in the C language. The pointer in C language stores the contents of the variable, the address in memory.   1. References to variables PHP allows you to use two variables to point to the same content     code as follows:     $a = "ABC";     $b =& $a;     echo $a//Here output: ABC     ECHO $b;//Here Output: ABC     $b = "EFG";     echo $a//Here the value of $a changes to EFG so output EFG     echo $b;//Here Output EFG?>   2. Reference passing (call to address) of functions I don't have to say more. The following directly gives Code     Code as follows: <?php       function test (& $a)     {        $a =$ a+100;    }     $b = 1;     echo $b//Output 1     test ($b);  //Here $b passed to the function is actually the $b variable content of the memory address, by changing the value of $a in the function can change the value of $b     echo "<br>";     echo $b//output?>     Note that in this case test (1), it will be wrong, the reason to think for themselves. Note: The above "Test" ($b); "In the $b before the & symbol, but in the function" Call_user_func_array ", to refer to the argument, you need the & symbol, as shown in the following code:     Code is as follows: <?php function A (& amp; $b) {    $b + +;} $c = 0; CaLl_user_func_array (' A ', Array (& $c)); Echo $c; Output 1?> 3. A reference to the function returns first look at the code code as follows: <?php function &test () {    static $b =0;//declares a static variable     $b = $b + 1;     Echo $b;     return $b; $a =test ();//This statement will output $b value of 1 $a = 5; $a =test ();//This statement outputs $b value of 2 $a =&test ();//This statement outputs $b value of 3 $a = 5; $a =test ();//This statement will output $b value of 6?>   below: this way $a=test (); The result is not the return of a reference to a function, which is no different from a normal function call. As for the reason: this is the PHP rule that PHP rules through $a=& Amp;test (); The way to get is the function of the reference to return as to what is the 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 which variable above.) This shit is killing me for half a day.   Using the above example to explain is $a =test () way to call the function, just assign the value of a function to $a, and $a make any changes that do not affect the $b in the function and call the function through $a=&test (), his role is Pointing the memory address of the $b variable in the return $b to the same place as the memory address of the $a variable produces the equivalent effect ($a =& $b;) So changing the value of the $a also changes the value of the $b so that in the execution of the $a =&test (); $a = 5; Later, the value of $b changed to 5   here is to let you understand the function of the reference to return to use static variables, in fact, the function of reference to return to more than the object   with a PHP official example:      code as follows: This is the Way how do we use pointer to access variable inside the class. <?php class talker{    Private $data = ' Hi ';     Public Function & get () {        return $this->data;    }     &nbs P 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     code as follows: <?php     class a{        var $abc = "abc";    }     $b =new A;     $c = $b;     echo $b->abc;//here output ABC     echo $c->abc;//here output ABC     $b->abc= "DEF";     echo $c->abc;//here output def?>   code is the run effect in PHP5   in PHP5 the assignment of an object is a reference process. The above $b=new A; $c = $b; is actually equivalent to $b=new A; $c =& $b; The default in PHP5 is to invoke an object by reference, but sometimes you might want to create a copy of an object and expect 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 $b is a copy of this anonymous object. The same $c= $b and a copy of the $b content. So in PhP4, in order to conserve memory space, $b =new A is generally changed to a reference mode, that is $b =& new A.   Here's an official example: in PHP5, you don't need to add anything extra to get to the "object reference" function:     Code as follows: <?php class foo{        protected $name;         function __construct ($str) {                $this-> name = $STR;        }         function __tostring () {                return   ' I name is '. $this->name. ' "and I live in". __class__. '".' . " n ";        }         function SetName ($str) {          &NBSP ;     $this->name = $str;        }} class masterone{        protected $foo;         F Unction __construct ($f) {                $tHis->foo = $f;        }         function __tostring () {                return ' Master: '. __class__. ' | Foo: '. $this->foo. "N";        }         function Setfooname ($str) {          &N Bsp     $this->foo->setname ($STR);        }} class mastertwo{        protected $foo;         F Unction __construct ($f) {                $this->foo = $f;                 function __tostring () {                return ' Master: '. __class__. ' | Foo: '. $this->foo. "N";        }         function Setfooname ($str) {          &N Bsp     $this->foo->setname ($STR); &nbsp      }} $bar = new foo (' Bar '); Print ("n"); Print ("Only Created $bar and printing $barn"); Print ($bar); Print ("n"); Print ("Now $baz are referenced to $bar and printing $bar and $BAZN");   $baz =& $bar; Print ($bar); Print ("n"); Print ("Now creating Masterone and two with passing $bar to both CONSTRUCTORSN");   $m 1 = new Masterone ($bar); $m 2 = new Mastertwo ($bar); Print ($m 1); Print ($m 2); Print ("n"); Print ("Now changing value of $bar and printing $bar and $BAZN");   $bar->setname (' Baz '); Print ($bar); Print ($baz); Print ("n"); Print ("Now printing again Masterone and Twon"); Print ($m 1); Print ($m 2); Print ("n"); Print ("Now changing Mastertwo ' s foo name and printing again Masterone and Twon");   $m 2->setfooname (' mastertwo ' Foo '); Print ($m 1); Print ($m 2); Print ("Also Printing $bar and $bazn"); Print ($bar); Print ($baz);?>     output:     Code as follows: only Created $bar and printing $bar the My name is "bar" and I Live in "foo". Now $baz are referenced to $bar and printing $bar and $baz the I 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 the I name is "Baz" and I live in "foo". The 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 ' foo" and I Live in "foo". Master:mastertwo | Foo:my name is "Mastertwo ' foo" and I Live in "foo". Also printing $bar and $baz My name are "Mastertwo ' foo" and I Live in "foo". The My name is "Mastertwo ' foo" and I Live in "foo".     Previous example parsing:   Code as follows: $bar = new Foo (' BAr '); $m 1 = new Masterone ($bar); $m 2 = new Mastertwo ($bar);   Instance Object $m1 and $m2 $bar is a reference to an instance $bar, not a copy, which is the characteristic of an object reference in PhP5, that is, 1. $m 1 or $M2, any operation on $bar affects the correlation value of the external object instance $bar. 2. Changes to the external object instance $bar also affect the $bar reference-related values within the $M1 and $m2.   in PhP4, the equivalent code (that is, a reference call) is similar to that of an object instance that is used in front of another object as described above: the     code is as follows: Class foo{   var $bar;    function Setbar (& $newBar) {      $this->bar =& newbar;    }}   5. The role of a reference if the process The order is bigger, the variable that references the same object is more, and want to use the object to remove it manually, personal suggestion uses "&" way, then clears with $var=null way. At other times, use the PHP5 default method. In addition, in PHP5 for large array of transmission, it is recommended to use the "&" mode, after all, save memory space use. 6. dereference when you unset a reference, just disconnect the variable name and the contents of the variable binding. This does not mean that the variable content has been destroyed. For example:      code as follows: <?php     $a = 1;     $b =& $a;     unset ($a)?> not unset $b, just $a.   7.global references a reference to a global variable is actually established when declaring a variable with the global $var. That is to do the same with the:  <?php     $var =& $GLOBALS ["var"];?>   This means that, for example, unset $var do not unset global variables.   If you assign a reference to a variable declared as global within a function, the reference is onlyVisible inside the function. You can avoid this by using a $GLOBALS array. Example   Reference global variables in functions     code as follows: <?php $var 1 = "Example variable"; $var 2 = ""; function global_references ($use _globals) {    global $var 1, $var 2     if (! $use _globals) {  &N Bsp     $var 2 =& $var 1; Visible only inside the function    } else {        $GLOBALS ["var2"] =& $var 1;//V Isible also in global context    } global_references (false); echo "VAR2 is set to ' $var 2 ' n"; VAR2 is set to ' global_references (true); echo "VAR2 is set to ' $var 2 ' n"; VAR2 is set to ' Example variable '?>   global $var; As $var =& $GLOBALS [' var ']; 's Shorthand. Thus assigning other references to the $var changes only the references to local variables.   8 $this in an object's method, $this is always a reference to the object that called it. Here's a little episode. The pointer to address (like pointers) in PHP is not implemented by the user itself, is implemented by the Zend Core, PHP refers to the use of "write-time copy" principle, unless a write operation, point to the same address variables or objects are not copied. Popular Talk 1: If there is the following code [CODE]<?     $a = "ABC";     $b =& $a?>     In fact, at this point $a and $b are pointing to the same memory address and not $a and$b occupy different memory 2: If you add the following code based on the above code     code as follows: <?php   $a = "EFG";?>   because the data of the memory pointed to by $a and $b is to be written again, At this point the Zend core automatically determines the automatic production of a $a data copy for $b, re-apply a piece of memory to store PHP references (that is, before variables or functions, objects, etc. plus & symbol) is a high-level topic, the novice more attention, the correct understanding of PHP reference is very important to have a greater impact on performance , 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 actually not the case, and it's a big difference. The pointer in C language is not explicitly declared except in the array pass. Other need to use * to define, and PHP for the address (like pointers) function is not implemented by the user, is implemented by the Zend Core, PHP referenced in the "write-time copy" principle, is unless Write, a variable or object that points to the same address is not copied, such as the following code:     Code as follows: $a = array (' A ', ' C ' ... '); $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 point to the same memory, which is the difference between PHP and C, do not need to write a $b=& $a to represent the $b point to $a memory, Zend has helped you implement the citation, and Zend will be very intelligent to help you determine when to do so and when to do so. If you continue to write the following code later, add a function, pass the argument by reference, and print out the array size.   Code as follows: Function PrintArray (& $arr)//reference delivery {   print (count ($arr));  }   PrintArray ($a); In the code above, we pass the $a array to the PrintArray () function, and the Zend Engine thinks that printarray () can cause a change to the $a, which automatically produces a $b copy of the data for $a and then requests a new memory for storage. This is the "write-time copy" concept mentioned earlier. If we change the above code to the following:   code as follows: function PrintArray ($arr)  //value Delivery {   print (Count ($arr)); } printArray ($a);   The above code passes the $a value directly to PrintArray (), there is no reference passing, so no write-time copy appears. You can test the performance of the above two lines of code, such as the outside to join a loop 1000 times, to see how time-consuming the operation, the results will let you know that incorrect use of the reference will lead to a decrease in performance by more than 30%. Self-understanding: According to the value of the word is not related to the parameters within the function, equivalent to the role of local variables, but by the word of the address (reference) is related to the parameters of the function, equivalent to the role of global variables. And from the performance side, 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.