Meaning and usage of PHP references

Source: Internet
Author: User
This article here to everyone full display of PHP reference, very detailed, collocation example, is a very good article, recommended for the needs of small partners to refer to.

What is a reference?

Referencing in PHP means accessing the same variable content with a different name. This is not like the C pointer, instead, the reference is the symbol table alias. Note that in PHP, variable names and variable contents are not the same, so the same content can have different names. The closest analogy is the Unix filename and the file itself-the variable name is the directory entry, and the variable content is the file itself. References can be seen as hardlink in Unix file systems.

Reference to do what

PHP references allow two variables to point to the same content. This means that when you do this:

The code is as follows:

<?php$a =& $b;? >

This means that $a and $b point to the same variable.

Note:

$a and $b are exactly the same here, not $a point to $b or vice versa, but $a and $b point to the same place.

Note:

If an array with a reference is copied, its value is not dereferenced. This is true for arrays that pass values to functions.

Note:

If a reference is assigned to an undefined variable, a reference parameter is passed, or a reference is returned, the variable is created automatically.

Example #1 use references to undefined variables

The code is as follows:

<?phpfunction foo (& $var) {}foo ($a); $a is "created" and assigned to Null$b = Array (); foo ($b [' B ']); Var_dump (array_key_exists (' B ', $b)); BOOL (true) $c = new Stdclass;foo ($c->d); Var_dump (Property_exists ($c, ' d ')); BOOL (TRUE)?>

The same syntax can be used in functions, it returns references, and is used in the new operator (PHP 4.0.4 and later versions):

The code is as follows:

<?php$bar =& new Fooclass (); $foo =& Find_var ($bar);? >

Since PHP 5, new automatically returns references, so using =& here is obsolete and generates E_STRICT-level messages.

Note:

Using the & operator causes the object to generate a copy. If $this in the class, it will be used for the current instance of the class. No assignment with & will copy this instance (such as an object) and $this will act on the copy, which is not always the desired result. Because of problems with performance and memory consumption, you usually just want to work on one instance.

Although you can use the @ operator to suppress any error information in the constructor, such as @new, this does not work with the &new statement. This is a limitation of the Zend engine and can result in a parsing error.

Warning

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 #2 referencing global variables within a function

The code is as follows:

<?PHP$VAR1 = "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 ' \ n"; VAR2 is set to ' global_references (true); echo "Var2 was set to ' $var 2 ' \ n"; 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.
Note:

If you assign a value to a variable that has a reference in the foreach statement, the referenced object is also changed.

Example #3 References and foreach statements

The code is as follows:

<?php$ref = 0; $row =& $ref; foreach (Array (1, 2, 3) as $row) {    //do something}echo $ref;//3-last element of The iterated array?>

The second thing a reference does is pass a variable by reference. This is done by creating a local variable within the function and referencing the same content within the call range. For example:

The code is as follows:

<?phpfunction foo (& $var) {    $var + +;    } $a =5;foo ($a);? >

Will make the $a into 6. This is because the variable $var in the Foo function points to the same content that the $a points to. For more detailed explanations see reference delivery.

The third thing a reference does is to refer back.

Reference is not what

As mentioned earlier, references are not pointers. This means that the following structure does not produce the expected effect:

The code is as follows:

<?phpfunction foo (& $var) {    $var =& $GLOBALS ["Baz"];} Foo ($bar);? >

This causes the $var variables in the Foo function to be bound together with the $bar when the function is called, but is then re-bound to the $GLOBALS ["Baz"]. It is not possible to bind $bar to other variables within the scope of a function call by means of a reference mechanism, because there is no variable $bar in the function foo (it is represented as a $var, but $var only the contents of the variable without calling the name-to-value binding in the symbol table). You can use a reference return to refer to the variable selected by the function.

Reference delivery

You can pass a variable to a function by reference, so that the function can modify the value of its argument. The syntax is as follows:

The code is as follows:

<?phpfunction foo (& $var) {    $var + +;} $a =5;foo ($a);//$a is 6 here?>

Note that there is no reference symbol in the function call-only in the function definition. The function definition alone is enough to make the argument pass through the reference correctly. In the most recent version of PHP, if the & is used in Foo (& $a); Will get a warning that "Call-time pass-by-reference" is out of date.

The following can be passed by reference:

variables, such as foo ($a)
New statement, such as Foo (new Foobar ())
The reference returned from the function, for example:

The code is as follows:

<?phpfunction &bar () {    $a = 5;    return $a;} Foo (bar ());? >

See the reference return for a detailed explanation.
No other expression can be passed by reference, and the result is undefined. For example, the following example of a reference pass is invalid:

The code is as follows:

<?phpfunction bar ()//Note The missing &{    $a = 5;    return $a;} Foo (bar ()); Fatal error since PHP 5.0.5 ($a = 5)//expression, not variable foo (5)//causes fatal error?>

These conditions are PHP 4.0.4 and later versions.

Reference returns
Reference returns are used when you want to use a function to find out which variable the reference should be bound to. Do not use return references to increase performance, and the engine is smart enough to optimize itself. Return references only if there are reasonable technical reasons! To return a reference, use this syntax:

The code is as follows:

<?phpclass Foo {public    $value =;    Public Function &getvalue () {        return $this->value;    }} $obj = new Foo; $myValue = & $obj->getvalue (); $myValue is a reference to $obj->value, which is $obj->value = 2;echo $myValue;                Prints the new value of $obj->value, i.e. 2.? >

In this case, the properties of the object returned by the GetValue function will be assigned, not copied, as opposed to the reference syntax.

Note: Unlike parameter passing, the & symbol must be used in two places-indicating that the return is a reference, not a normal copy, and also that the $myValue is the binding as a reference, not the usual assignment.

Note: If you try to return a reference from a function like this: return ($this->value), this will not work because you are trying to return the result of an expression instead of a referenced variable. Reference variables can only be returned from functions-no other way. If the code tries to return the result of a dynamic expression or the new operator, a e_notice error is issued from PHP 4.4.0 and PHP 5.1.0.

The code is as follows:

<?phpfunction &test () {     static $b =0;//declares a static variable     $b = $b +1;     echo $b;     return $b; } $a =test ();//This statement outputs a value of $b of 1 $a = 5; $a =test ();//This statement outputs a value of $b of 2$a=&test ();//This statement outputs a value of $b of 3 $a = 5; $a =test ();//This statement outputs a value of $b 6?>

$a =test () call the function, just assign the value of the function to $ A, and $ A does nothing to change the $b in the function, and call the function by $a=&test (), his function is to return the memory address of the $b variable in the $b with the $ The memory address of a variable points to the same place, which produces the equivalent effect ($a =&b;) So change the value of $ A and change the value of the $b at the same time, so the $a =&test is executed (); $a = 5; Later, the value of the $b becomes 5.

Dereference

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

The code is as follows:

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

Not unset $b, just $a.

It might help to understand that this analogy with Unix's unlink.

Reference positioning

Many of the syntax structures of PHP are implemented by reference mechanisms, so all of the above reference bindings apply to these constructs as well. Some structures, such as reference passing and return, have already been mentioned above. Other structures that use references are:

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:

The code is as follows:

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

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

Using unset ($a) is not the same as the result of $a=null. If the block memory only a $ A mapping, then unset ($a) and $a=null equivalent, the memory reference count becomes 0, is automatically recycled, if the block memory has $ A and $b two mappings, then unset ($a) will cause $a=null and $b, and $a= Null causes $a= to $b =null.

Cause: A variable is assigned null, which causes the reference count of the memory block corresponding to the variable to be set directly to 0 and is automatically reclaimed.

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

The role of references

If the program is larger, referencing the same object is more variable, and you want to use the object after the manual removal of it, the personal suggestion "&" method, and then $var=null to clear. 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.

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

The code is as follows:

<?ph$a= "ABC"; $b = $a;? >

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

2: If you add the following code based on the above code

The code is as follows:

$a = "EFG";

Since $ A and $b point to the memory of the data to be re-written once, at this time the Zend core will automatically decide to automatically produce a $ A copy of the data for $b, re-request a piece of memory for storage.

Summary : The above is the entire content of this article, I hope to be able to help you learn.

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.