PHP Reference (&) A variety of examples of using methods _php examples

Source: Internet
Author: User
Tags zend

PHP references (in addition to the variables or functions, objects, etc. before the & symbol), in PHP refers to the meaning: different names to access the same variable content. There is a difference between the pointers in the C language. The pointer in C language stores the contents of the variable, the address in memory.

1. References to variables
PHP references allow you to use two variables to point to the same content

Copy Code code as follows:
?
$a = "ABC";
$b =& $a;
echo $a//here output: ABC
echo $b//Here Output: ABC
$b = "EFG";
echo $a//The value of $a here becomes EFG so output EFG
echo $b//Here output EFG
?>

2. Reference Pass of function (call to address)
I'm not going to say more than that. The following directly gives the code

Copy Code code as follows:
<?php

Function test (& $a)
{
$a = $a +100;
}
$b = 1;
echo $b;//Output 1
Test ($b); Here $b passed to the function is actually the $b variable content of the memory address, by changing the value of $a in the function can change the value of $b
echo "<br>";
echo $b;//Output 101
?>

Note that in this case test (1), the words will be wrong, the reason to think for themselves.
Note: The above "Test" ($b); "In the $b, do not precede the & symbol, but in the function" Call_user_func_array ", to refer to the argument, you need the & symbol, as shown in the following code:

Copy Code code as follows:
<?php
Function A (& $b) {
$b + +;
}
$c = 0;
Call_user_func_array (' A ', Array (& $c));
Echo $c;
Output 1
?>

3. The reference of the function returns
Look at the code first

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 will output $b value of 1
$a = 5;
$a =test ()//This statement will output $b value of 2
$a =&test ()//This statement will output $b value of 3
$a = 5;
$a =test ()//This statement will output $b value of 6
?>

The following explains:
$a=test in this way (); What you get is not the return of a reference to a function, which is no different from a normal function call. As for the reason: this is the PHP rule
PHP rules through $a=&test (); The way to get the function is to return the reference
As for what is the reference return (PHP manual says: Reference returns used when you want to use a function to find the reference should be bound to which variable above.) This shit is killing me for half a day.

The example above is to explain
Calling a function $a =test () simply assigns the value of the function to $a, and $a does nothing to affect the $b in the function
Instead of calling the function by $a=&test (), his role is to point the memory address of the $b variable in the return $b to the same place as the $a variable's memory address
That 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 $b changed to 5.

Here is to let you understand the function of reference to return to use static variables, in fact, the function of reference return is more used in the object

Another example of a PHP official:

Copy Code code as follows:
This is the way how do we use pointer to access variable inside the class.
<?php
Class talker{
Private $data = ' Hi ';
Public Function & get () {
return $this->data;
}

Public function out () {
Echo $this->data;
}
}
$AA = new talker ();
$d = & $aa->get ();
$aa->out ();
$d = ' how ';
$aa->out ();
$d = ' Are ';
$aa->out ();
$d = ' you ';
$aa->out ();
?>
The output is "hihowareyou"

4. References to Objects

Copy Code code as follows:
<?php
Class a{
var $abc = "abc";
}
$b =new A;
$c = $b;
echo $b->abc;//here output ABC
echo $c->abc;//here output ABC
$b->abc= "DEF";
echo $c->abc;//here output def
?>

The code on is the effect 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 an object by reference, but sometimes you might want to create a copy of an object and expect 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,
For example: $b =new A, where new a produces an anonymous instance of a object, at which point $b is a copy of the anonymous object. The same $c= $b and a copy of the $b content. So in PhP4, in order to conserve memory space, $b =new A is generally changed to a reference mode, that is $b =& new A.

Here's another example of an official offer:
In php5, you don't need to add anything extra to get to the "object reference" feature:

Copy Code code as follows:
<?php
Class foo{
protected $name;
function __construct ($STR) {
$this->name = $str;
}
function __tostring () {
Return ' I name is '. $this->name. ' "and I live in". __class__. '".' . " \ n ";
}
function SetName ($STR) {
$this->name = $str;
}
}
Class masterone{
protected $foo;
function __construct ($f) {
$this->foo = $f;
}
function __tostring () {
Return ' Master: '. __class__. ' | Foo: '. $this->foo. "\ n";
}
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. "\ n";
}
function Setfooname ($STR) {
$this->foo->setname ($STR);
}
}
$bar = new Foo (' Bar ');
Print ("\ n");
Print ("Only Created \ $bar and printing \ $bar \ n");
Print ($bar);
Print ("\ n");
Print ("Now \ $baz are referenced to \ $bar and printing \ $bar and \ $baz \ n");

$baz =& $bar;
Print ($bar);
Print ("\ n");
Print ("Now creating Masterone and two with passing \ $bar to both constructors\n");

$m 1 = new Masterone ($bar);
$m 2 = new Mastertwo ($bar);
Print ($m 1);
Print ($m 2);
Print ("\ n");
Print ("Now changing value of \ $bar and printing \ $bar and \ $baz \ n");

$bar->setname (' Baz ');
Print ($bar);
Print ($baz);
Print ("\ n");
Print ("Now printing again Masterone and two\n");
Print ($m 1);
Print ($m 2);
Print ("\ n");
Print ("Now changing Mastertwo ' s foo name and printing again Masterone and two\n");

$m 2->setfooname (' mastertwo\ ' Foo ');
Print ($m 1);
Print ($m 2);
Print ("Also printing \ $bar and \ $baz \ n");
Print ($bar);
Print ($baz);
?>

Output:

Copy Code code as follows:
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 two 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
The My name is "Baz" and I live in "foo".
The My name is "Baz" and I live in "foo".
Now printing again Masterone and two
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 two
Master:masterone | Foo:my name is "Mastertwo ' foo" and I Live in "foo".
Master:mastertwo | Foo:my name is "Mastertwo ' foo" and I Live in "foo".
Also Printing $bar and $baz
The My name is "Mastertwo ' foo" and I Live in "foo".
The My name is "Mastertwo ' foo" and I Live in "foo".


The last example resolves:

Copy Code code as follows:
$bar = new Foo (' Bar ');
$m 1 = new Masterone ($bar);
$m 2 = new Mastertwo ($bar);

The $bar in the instance object $m1 and $m2 is a reference to the instance $bar, not a copy, which is the characteristic of the object reference in PhP5, which means
1. Within $m 1 or $m2, any action on $bar affects the correlation values of the external object instance $bar.
2. Changes to the external object instance $bar also affect the $bar reference-related values within the $M1 and $m2.

In PhP4, the equivalent code (that is, a reference invocation) is similar to implementing an object instance as described above in the presence of another object's properties, as follows:

Copy Code code as follows:
Class foo{
var $bar;
Function Setbar (& $newBar) {
$this->bar =& Newbar;
}
}

5. The role of 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.
6. dereference
When you 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.
7.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:
<?php
$var =& $GLOBALS ["var"];
?>
This means, for example, that unset $var does not unset global variables.
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 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.

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 for the address of the point (like pointers) function is not implemented by the user, is implemented by the Zend Core, PHP refers to the use of "write-time copy" principle is that unless there is 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
[Code]<?
$a = "ABC";
$b =& $a;
?>

In fact, at this point $a and $b are pointing 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

Copy Code code as follows:
<?php
$a = "EFG";
?>

Because the $a and $b point to the memory of the data to be written again, at this time the Zend core will automatically judge automatically for $b production of a $a copy of the data, reapply a piece of memory for storage
PHP references (that is, the variables or functions, objects, etc. before the addition of & symbol) is a high-level topic, the novice more attention, the correct understanding of PHP reference is very important to performance has a greater impact, and understand the error may lead to program errors!
Many people misunderstand that the reference in PHP is the same as the pointer in C, which is actually not the case, and it's a big difference. The pointer in C language is not explicitly declared except in the array pass. Other need to use * to define, and PHP for the address (like pointers) function is not implemented by the user, is implemented by the Zend Core, PHP referenced in the "write-time copy" principle, is unless Write, a variable or object that points to the same address is not copied, such as the following code:

Copy Code code as follows:
$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 point to the same memory, which is the difference between PHP and C, do not need to write a $b=& $a to represent the $b point to $a memory, Zend has helped you implement the citation, and Zend will be very intelligent to help you determine when to do so and when to do so.
If you continue to write the following code later, add a function, pass the argument by reference, and print out the array size.
Copy Code code as follows:
Function PrintArray (& $arr)//reference delivery
{
Print (count ($arr));

}


PrintArray ($a);
In the code above, we pass the $a array to the PrintArray () function, and the Zend Engine thinks that printarray () can cause a change to the $a, which automatically produces a $b copy of the data for $a and then requests a new memory for storage. This is the "write-time copy" concept mentioned earlier.
If we change the above code to the following:
Copy Code code as follows:
function PrintArray ($arr)//value delivery
{
Print (count ($arr));
}
PrintArray ($a);

The above code passes the $a value directly to PrintArray (), there is no reference passing, so no write-time copy appears.
You can test the performance of the above two lines of code, such as the outside to join a loop 1000 times, to see how time-consuming the operation, the results will let you know that incorrect use of the reference will lead to a decrease in performance by more than 30%.
Self-understanding: According to the value of the word is not related to the parameters within the function, equivalent to the role of local variables, but by the word of the address (reference) is related to the parameters of the function, equivalent to the role of global variables. And from the performance side, look at the above analysis is enough.

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.