In-depth analysis of PHP reference (&), in-depth analysis of php reference _ PHP Tutorial

Source: Internet
Author: User
Tags php books
In-depth analysis of PHP references (& amp;), in-depth analysis of php references. In-depth analysis of PHP references (lt; php $ a, which means that $ a and $ B point to the same variable. Note: $ a and $ B are exactly the same here. this doesn't mean $ a points to $ B or vice versa. Instead, it analyzes PHP references (&) in depth and php references in depth.

Reference
Referencing in PHP means accessing the same variable content with different names. This is not like the pointer of C. Instead, the reference is the alias of the symbol table. Note that in PHP, the variable name and variable content are different, so the same content can have different names. The closest analogy is the Unix file name and the file itself-the variable name is a directory entry, while the variable content is the file itself. A reference can be considered as a hardlink in a Unix file system.

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

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

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

Note:

$ A and $ B are exactly the same here. this doesn't mean $ a points 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 removed from the reference. This is also true for passing values from arrays to functions.

Note:

If an undefined variable is referenced, assigned, referenced, or returned, the variable is automatically created.

Example #1 use reference for undefined variables

<?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, which return references, and in the new operator (PHP 4.0.4 and later versions ):

<?php$bar =& new fooclass();$foo =& find_var($bar);?>


Since PHP 5, new automatically returns a reference. Therefore, when = & is used here, messages at the E_STRICT level will be generated.

Note:

No & operator is used to generate a copy of the object. If $ this is used in the class, it will act on the current instance of the class. The instance (such as an object) will be copied without a value & and $ this will apply to this copy, which is not always the desired result. Due to performance and memory consumption problems, you usually only want to work on one instance.

Although the @ operator can be used to suppress any error information in the constructor, such as @ new, it does not work when the & new statement is used. This is a limitation of the Zend Engine and may cause a parsing error.

Warning

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 #2 reference global variables in the function

<?php$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'\n"; // var2 is set to ''global_references(true);echo "var2 is set to '$var2'\n"; // 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.
Note:

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

Example #3 references and foreach statements

<?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 to do with referencing is to use referencing to pass variables. This is achieved by creating a local variable in the function and referencing the same content in the call range. For example:

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

Changes $ a to 6. This is because the variable $ var points to the same content as $ a in the foo function. For more detailed explanations, refer to transfer references.

The third thing that references is to return a reference.

Reference is not
As mentioned above, the reference is not a pointer. This means that the following structure will not produce the expected results:

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

This binds the $ var variable in the foo function to $ bar when calling the function, but is then re-bound to $ GLOBALS ["baz. It is impossible to bind $ bar to another variable within the function call range through the reference mechanism, because there is no variable $ bar in function foo (it is represented as $ var, but $ var only contains the variable content and does not call the name-to-value binding in the symbol table ). You can use the reference return to reference the variable selected by the function.

Reference transfer
A variable can be passed to the function through reference, so that the function can modify the value of its parameter. Syntax:

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

Note that there is no reference symbol when calling a function-only in the function definition. Function definition is enough to make parameters pass through references correctly. In the latest PHP version, if you use & in foo (& $ a);, you will receive a warning that "Call-time pass-by-reference" is out of date.

The following content can be passed through reference:

Variable, such as foo ($)
New statement, such as foo (new foobar ())
Reference returned from the function, for example:

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

For more information, see return references.
No other expressions can be passed through references, and the results are undefined. For example, the example passed by reference below is invalid:

<? Phpfunction bar () // Note the missing & {$ a = 5; return $ a;} foo (bar ()); // cause fatal error foo ($ a = 5) from PHP 5.0.5 // expression, not variable foo (5) // cause fatal error?>

These conditions are available in PHP 4.0.4 and later versions.

Reference return
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. Do not use return references to increase performance. the engine is smart enough for optimization. A reference is returned only when there are reasonable technical reasons! To return a reference, use this syntax:

<?phpclass foo { public $value = 42; public function &getValue() {  return $this->value; }}$obj = new foo;$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.$obj->value = 2;echo $myValue;    // prints the new value of $obj->value, i.e. 2.?>

In this example, the attributes of the objects returned by the getValue function will be assigned, rather than being copied, just like the reference syntax.

Note: Unlike parameter transfer, the & symbol must be used here to indicate that a reference is returned instead of a normal copy. it also indicates that $ myValue is bound as a reference, instead of assigning values normally.

Note: If you try to return the reference from the function like this: return ($ this-> value);, this will not work because you are trying to return the result of an expression rather than a referenced variable. Only variables can be referenced from function return-no other method. If the code tries to return the result of a dynamic expression or new operator, an E_NOTICE error will be issued since PHP 4.4.0 and PHP 5.1.0.

<? Phpfunction & test () {static $ B = 0; // declare a static variable $ B = $ B + 1; echo $ B; return $ B ;} $ a = test (); // This statement will output the value of $ B as 1 $ a = 5; $ a = test (); // This statement outputs the value of $ B as 2 $ a = & test (); // This statement outputs the value of $ B as 3 $ a = 5; $ a = test (); // This statement outputs the value of $ B as 6?>

$ A = test () is used to call a function. it only assigns the value of the function to $ a. If $ a is changed, $ B in the function is not affected, but how to call a function through $ a = & test, the function is to direct 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, so the value of $ a is changed and the value of $ B is also changed, therefore, after $ a = & test (); $ a = 5; is executed, the value of $ B is changed to 5.

Cancel reference
When unset is a reference, it only disconnects the binding between the variable name and the variable content. This does not mean that the variable content is destroyed. For example:

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

Not unset $ B, just $.

It may be helpful to understand this analogy with the Unix unlink call.

Reference and positioning
Many PHP syntax structures are implemented through the reference mechanism, so all the above-mentioned reference binding applies to these structures. Some structures, such as reference transfer and return, have been mentioned above. Other referenced structures include:

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:

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

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

The unset ($ a) and $ a = null results are different. If the block memory only has $ a ING, the unset ($ a) is equivalent to $ a = null, and the reference count of the memory is changed to 0, which is automatically recycled; if the block memory has ing between $ a and $ B, unset ($ a) causes $ a to be null and $ B to remain unchanged, $ a = null may cause $ a = $ B = null.

Cause: if the value of a variable is null, the reference count of the memory block corresponding to the variable is directly set to 0, which is automatically recycled.

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

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.

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:

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

In fact, both $ a and $ B point to the same memory address, instead of occupying different memory for $ a and $ B.

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 automatically determines that $ B will generate a $ a data copy, apply for a new memory for storage.


Simple PHP loop call

This should be in the dz template.
Meaning:

Loop $ look_cates assigned to $ book_cate
If $ book_cate ['type'] is equal to cate
Assign the value of $ book_cate ['data'] to $ book_cate.

After the template is parsed, the following conditions are met:
Foreach ($ book_cates as $ book_cate ){
If ($ book_cakte ['type'] = 'Cate '){

$ Book_cate = $ book_cate ['data'];

}

}

?>

In-depth introduction to PHP books

Analyze the good code. recommended for books < <代码之美> > Books that all programmers should read

Except (lt; php $ a = this means that $ a and $ B point to the same variable. Note: $ a and $ B are exactly the same here. this is not because $ a points to $ B or vice versa,...

Related Article

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.