PHP references (&) details and Considerations _php Tutorial

Source: Internet
Author: User

PHP references (&) details and considerations


PHP references (that is, a variable or function or object or object method preceded by a & symbol)

The reference in PHP means: 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.

 
  

2. function Reference passing (call to address)

Address call I will not say more, the following direct code:

 
  "; Echo $b; Output 101?>

Note that the test (1) is here; The words will go wrong, cause to think for yourself.

Attention:

The "test" above ($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:

 
  

3. A reference to a function returns

Look at the code first:

 
  

The following explanation:

In this way $a =test (); The resulting is not the function of the reference return, which is not the same as the normal function call, as for the reason: this is the PHP rules.

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 nonsense, I did not understand the day.

This is explained by the example above:

$a = Test () calls the function, just assigns the value of the function to $ A, and $ A does nothing to affect the $b in the function, and the function is called by $a = &test () , it is the function of return $ The memory address of the $b variable in B and the memory address of the $ A variable point to the same place, which produces the equivalent effect ($a = & $b;) so changing the value of $ A also changes the value of $b, so the

$a = &test (); $a = 5;

Later, the value of the $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:

 
  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

 
  abc Here output Abcecho $c->abc; Here output abc$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.

Here's an example of the official offer:

In PHP5, you don't need to add anything extra to get to the "object reference" feature:

 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 ');p rint ("");p rint ("Created $bar and Printing $bar");p rint ($bar);p rint ("");p rint ("Now $baz is R Eferenced to $bar and printing $bar and $baz "), $baz = & $bar;p rint ($bar);p rint (" ");p rint (" Now Creating Masterone and Both and passing $bar to both constructors "), $m 1 = new Masterone ($bar), $m 2 = new Mastertwo ($bar);p rint ($m 1);p rint ($m 2);p Rin T ("");Print ("Now changing value of $bar and printing $bar and $baz") $bar->setname (' Baz ');p rint ($bar);p rint ($baz);p rint ("" );p rint ("Now printing again Masterone and both");p rint ($m 1);p rint ($m 2);p rint ("");p rint ("Now changing Mastertwo ' s foo Name and printing again Masterone and "), $m 2->setfooname (' mastertwo\ ' s Foo ');p rint ($m 1);p rint ($m 2);p rint (" Also Printing $bar and $baz ");p rint ($bar);p rint ($baz);? >

Output:

Only Created $bar and printing $bar
My name is ' bar ' and I live in ' foo '. Now $baz are referenced to $bar and printing $bar and $baz
My name is ' bar ' and I live in ' foo '. Now Creating Masterone and both 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
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
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".

Last Example Analysis:

$bar = new Foo (' Bar '), $m 1 = new Masterone ($bar);

The $bar in the instance object $m1 and $m2 is a reference to the instance $bar, not a copy, which is the feature of the object reference in PHP5, which means

    1. $m 1 or $M2, any action on $bar affects the relative value of the external object instance $bar.
    2. Changes to the external object instance $bar also affect the $bar reference related values within $M1 and $m2.

In PHP4, the equivalent code (that is, a reference call) is similar to the following when you use an object instance to go to the property in front of another object:

Class Foo{var $bar, Function Setbar (& $newBar) {$this->bar = $newBar;}}

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:

 
  

Not unset $b, just $a.

7.global references

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

 
  

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 $GLOBALS avoid this by using arrays.

Example referencing global variables within a function

 
  

Take global $var as a shorthand for $var = & $GLOBALS [' var ']; 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 called it.

Here's a little episode.

PHP in the direction of the address (similar to the pointer) function is not implemented by the user itself, is implemented by the Zend Core, PHP refers to the use of "copy-on- write " principle, that is, unless a write operation, the same address to the variable or object is not copied.

The popular Speaking

1: If you have the following code

 
  

In fact, $a and $b both point 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

 
  

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 *, while the point-of-reference (similar pointer) function in PHP is not implemented by the user itself, it is implemented by the Zend Core, PHP refers to the use of "copy-on- write " principle Is that unless a write 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.

Articles you may be interested in

    • PHP Security Programming considerations
    • How to use Curl's post submission data in PHP and get a summary of how to get Web page data
    • The use of return in PHP recursive functions should be noted
    • Site Space Security Considerations
    • thinkphp Summary of how to use the built-in template engine
    • PHP uses Array_flip to implement array key-value Exchange to remove array duplicate values
    • PHP uses regular filters to filter various tags, spaces, line break codes
    • PHP implements the simplest method of MVC development, model thinking

http://www.bkjia.com/PHPjc/892951.html www.bkjia.com true http://www.bkjia.com/PHPjc/892951.html techarticle PHP references (amp; symbols) are referenced in PHP to mean that different names access the same variable content. There is a difference between the pointers in the C language. C language in the pointer is stored in a 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.