PHP reference details, PHP reference details _ PHP Tutorial

Source: Internet
Author: User
PHP references and PHP references. PHP reference details, PHP reference details reference what is referenced in PHP means that different names are used to access the same variable content. This is not like the pointer of C. Instead, the reference is the reference of the symbol PHP.

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:

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

The code is as follows:


<? Php
Function 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 ):

The code is as follows:


<? 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

The code is as follows:


<? 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''
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

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

The code is as follows:


<? Php
Function foo (& $ var)
{
$ Var ++;
}

$ A = 5;
Foo ($ );
?>

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:

The code is as follows:


<? Php
Function 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:

The code is as follows:


<? Php
Function foo (& $ var)
{
$ Var ++;
}
$ A = 5;
Foo ($ );
// $ 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:

The code is as follows:


<? Php
Function & bar ()
{
$ A = 5;
Return $;
}
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:

The code is as follows:


<? Php
Function bar () // Note the missing &
{
$ A = 5;
Return $;
}
Foo (bar (); // fatal error caused by PHP 5.0.5
Foo ($ a = 5) // expression, not a variable
Foo (5) // cause a 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:

The code is as follows:


<? Php
Class 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.

The code is as follows:


<? Php
Function & test (){
Static $ B = 0; // declare a static variable
$ B = $ B + 1;
Echo $ B;
Return $ B;
}
$ A = test (); // This statement outputs 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 to 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:

The code is as follows:


<? Php
$ A = 1;
$ B = & $;
Unset ($ );
?>

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:

The code is as follows:


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

The code is as follows:


<? Ph
$ A = "ABC ";
$ B = $;
?>

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:

The code is as follows:


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

The above is all about PHP reference. I hope you will like it.

What is a callback reference in PHP means that the same variable content is accessed with different names. This is not like the pointer of C. Instead, the reference is a symbol...

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.