PHP Quotes detailed _php Tips

Source: Internet
Author: User
Tags function definition parse error zend

What is the reference?

Referencing in PHP means accessing the contents of the same variable with a different name. This is not like a C pointer, but instead, the reference is a symbolic 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 file name and the file itself-the variable name is the directory entry, and the variable content is the file itself. References can be viewed as hardlink in Unix file systems.

What does the reference do

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

Copy Code code 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 pointing to $b or vice versa, but $a and $b pointing to the same place.

Note:

If an array with a reference is copied, its value is not lifted. The same is true for arrays passing values to functions.

Note:

If a reference assignment to an undefined variable, a reference parameter pass, or a reference return is made, the variable is created automatically.

Example #1 Use a reference to an undefined variable

Copy Code code 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 are used in the new operator (PHP 4.0.4 and later versions):

Copy Code code 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:

The use of the & operator causes the object to generate a copy. If $this in a class, it will be used for the current instance of the class. It is not always the desired result to copy this instance (such as objects) without assigning the & and $this will work on the copy. Because of performance and memory consumption problems, you usually just want to work on one instance.

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

Warning

If you assign a reference to a variable declared as global within a function, the reference is visible only inside the function. You can avoid this by using a $GLOBALS array.

Example #2 Reference global variables within a function

Copy Code code as follows:

<?php
$var 1 = "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 the 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 '
?>

$var the global; As $var =& $GLOBALS [' var ']; 's Shorthand. Thus assigning other references to the $var changes only the references to local variables.
Note:

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

Example #3 References and foreach statements

Copy Code code 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 to pass a variable with a reference. This is done by creating a local variable within the function and referencing the same content within the call scope. For example:

Copy Code code as follows:

<?php
function foo (& $var)
{
$var + +;
}

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

will make $a into 6. This is because the variable $var points to the same content that the $a points to in the Foo function. See the reference pass for more detailed explanations.

The third thing a reference does is a reference return.

References are not

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

Copy Code code as follows:

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

This will cause the $var variable in the Foo function to be bound to the $bar at the time of the function call, but then to be rebind to the $GLOBALS ["Baz"]. It is not possible to bind a $bar to another variable in the scope of a function call through a reference mechanism, because there is no variable $bar in the function foo (it is represented as $var, but $var only the variable content but not the binding of the name to the value in the symbol table). You can use reference returns to refer to variables that are selected by the function.

Reference delivery

A variable can be passed to a function by reference, so that the function can modify the value of its arguments. The syntax is as follows:

Copy Code code as follows:

<?php
function 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 sufficient to pass the argument correctly by reference. In the most recent version of PHP if the & 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:

Copy Code code as follows:

<?php
function &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 reference pass example is invalid:

Copy Code code as follows:

<?php
function bar ()//Note the missing &
{
$a = 5;
return $a;
}
Foo (bar ()); Fatal error since PHP 5.0.5
Foo ($a = 5)//expression, not variable
Foo (5)//lead to fatal error
?>

These conditions are available in PHP 4.0.4 and later versions.

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

Copy Code code 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 properties of the object returned by the GetValue function are assigned, not copied, as if they were not referenced by reference syntax.

Note: Unlike parameter passing, there must be a & symbol in all two places--it indicates that the return is a reference rather than a common copy, and also that $myValue is a reference binding rather than a normal assignment.

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

Copy Code code as follows:

<?php
function &test () {
Static $b =0;//declares a statically variable
$b = $b +1;
Echo $b;
return $b;
}
$a =test ();//This statement outputs the $b value of 1
$a = 5; $a =test ();//This statement outputs the $b value of 2
$a =&test ();//This statement outputs the $b value of 3
$a = 5; $a =test ();//This statement outputs the $b value of 6
?>

$a =test () way to call a function, just the value of the function to $a only, and $a do any change will not affect the $b in the function, and through the $a=&test () way to call the function, and his role is to return $b the $b variable in the memory address and $ The memory address of a variable points to the same place, which produces the equivalent effect ($a =&b;) So changing the value of the $a also changes the value of the $b, so in the execution of the $a =&test (); $a = 5; Later, the value of the $b changed to 5.

Dereference

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

Copy Code code as follows:

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

Not unset $b, just $a.

Taking this analogy with Unix's unlink may help to understand.

Reference positioning

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

Global reference

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

Copy Code code as follows:

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

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

The results of using unset ($a) and $a=null are not the same. If the block memory has only $a a map, then unset ($a) is equivalent to $a=null, the reference count of the memory becomes 0 and is automatically reclaimed, and if the block memory has $a and $b two mappings, then unset ($a) will cause $a=null and $b the same situation, $a= Null can cause $a= $b =null.

Reason: A variable assignment is null, which causes the reference count of the memory block corresponding to the variable to be set directly to 0 and automatically recycled.

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

The role of a reference

If the program is larger, the number of references to the same object is more, and you want to use the object to remove it manually, personal advice to use the "&" mode, and then clear the $var=null. 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.

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.

In layman's terms.

1: If you have the following code

Copy Code code as follows:

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

In fact at this point, $a and $b are pointing to the same memory address, rather than $a and $b occupy different memory.

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

Copy Code code as follows:

$a = "EFG";

Since $a and $b point to the memory of the data to be written again, at this time the Zend core will automatically determine the $b production of a $a copy of the data, reapply a piece of memory for storage.

The above is about the full content of PHP reference, I hope you can enjoy.

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.