PHP Reference (&) using the _php tutorial

Source: Internet
Author: User

PHP references (&) use a detailed, PHP reference


Beginner PHP About & citations

Official documents:

1. What is a quote: http://www.php.net/manual/zh/language.references.whatare.php

2. What to do: http://www.php.net/manual/zh/language.references.whatdo.php
3. Reference delivery: http://www.php.net/manual/zh/language.references.pass.php
4. Reference return: http://www.php.net/manual/zh/language.references.return.php

PHP references (add & symbols before variables or functions, objects, etc.)

The reference in PHP means: Different names access the same variable content.
There is a difference between the pointers in the C language. The pointer inside the C language stores the contents of the variable, storing the address in memory.

1. References to variables

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

$a = "ABC";
$b =& $a;
echo $a;//output here: ABC
echo $b;//output here: ABC
$b = "EFG";
echo $a;//The value of $ A here becomes EFG so the output EFG
echo $b;//Output EFG here
?>


2. Function reference passing (call to address )

Address call I'm not going to say much. Directly below the code

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


It is important to note that here Test (1), the words will be wrong, reason to think.

Attention:

The "test" above ($b); Do not add the & symbol in front of the $b, but in the function "call_user_func_array", to reference the arguments, you need the & symbol, as shown in the following code:


Function A (& $b) {
$b + +;
}
$c = 0;

Call_user_func_array (' A ', Array (& $c));

Echo $c;

Output 1

?>



3. A reference to a function returns

Look at the code first

function &test ()
{
Static $b =0;//declaration of a statically 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 of 6
?>


The following explanation:
In this way $a=test (); The result is not a function reference return, which is not the same as a normal function call. The reason: It's php's rule.
PHP rules through $a=&test (); The way to get is the reference to the function is returned
As for what is a reference return (the PHP manual says that reference return is used when you want to use a function to find out which variable the reference should be bound to.) I haven't read this bullshit.

In the example above, the explanation is
$a =test () call the function, just assign the value of the function to $ A, and no change to $ A will affect the $b in the function.
by $a=&test (), the function is to call the memory address of the $b variable in the return $b to the same place as the memory address of the $ A variable.
That produces the equivalent effect ($a =& $b;) So changing the value of $ A also changes the value of the $b so that it executes the
$a =&test ();
$a = 5;
Later, the value of the $b becomes 5

This is to let you understand that the function reference returns only use static variables, in fact, the function of the reference return is more used in the object

Also attached is a PHP official example:

This is the the-the-pointer to access variable inside the class.

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 = ' is ';
$aa->out ();
$d = ' you ';
$aa->out ();
?>

The output is "hihowareyou"

4. References to Objects

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 above code is the result 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 the object by reference, but sometimes you might want to make a copy of the object, and you want 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,

such as: $b =new A, where new a produces an anonymous instance of a object, at which point the $b is a copy of the anonymous object. Similarly $c= $b and a copy of the $b content. So in PhP4, in order to save memory space, $b =new A is generally changed into a reference mode, that is, $b =& new A.

Here's an example of the official offer:

In php5, you don't need to add anything extra to get to the "object reference" feature:

Class foo{
protected $name;
function __construct ($STR) {
$this->name = $str;
}
function __tostring () {
Return ' My 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 both and 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:

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 both 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
My name is ' Baz ' and I live in ' foo '.
My name is ' Baz ' and I live in ' foo '.

Now printing again Masterone and
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
Master:masterone | Foo:my name is "Mastertwo's foo" and I Live in "foo".

Master:mastertwo | Foo:my name is "Mastertwo's foo" and I Live in "foo".

Also Printing $bar and $baz
My name is "Mastertwo's foo" and I Live in "foo".
My name is "Mastertwo's foo" and I Live in "foo".

Last Example Analysis:
$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 feature of the object reference in PhP5, which means
1. $m 1 or $M2, any operation on $bar will affect the value of the external object instance $bar.
2. Changes to the external object instance $bar also affect the $bar reference related values within $M1 and $m2.

In PhP4, the equivalent code (that is, a reference call) is similar to the following when you use an object instance to go to the property in front of another object:

Class foo{
var $bar;
Function Setbar (& $newBar) {
$this->bar =& NewBar;
}
}

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


6. dereference
When you unset a reference, you just break the binding between the variable name and the variable content. This does not mean that the contents of the variable are destroyed. For example:

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



Not unset $b, just $a.


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

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


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

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

Example referencing global variables within a function

$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 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 '
?> Put Global $var;As a $var =& $GLOBALS [' var '];The shorthand. So that other references are assigned to the $varOnly changes the reference to the local variable.

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 in the direction of the address (similar to the pointer) function is not implemented by the user itself, is implemented by the Zend Core, PHP refers to the use of "copy-on-write" principle, that is, unless a write operation, the same address to the variable or object is not copied.

The popular Speaking
1: If you have the following code

$a = "ABC";
$b =& $a;
?>


In fact, $a and $b both point 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

$a = "EFG";
?>


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

PHP references (that is, variables or functions, objects, etc. with & symbols) is a high-level topic, novice more attention, the correct understanding of PHP reference is very important, the performance has a large impact, and understanding errors can lead to program errors!

Many people misunderstand that the reference in PHP is the same as the pointer in C, which is not, in fact, very different. In addition to the pointer in the C language not explicitly stated in the process of the array, the others need to be defined using *, and PHP's point-of-address (similar pointer) function is not implemented by the user itself, is implemented by the Zend Core, PHP refers to the use of "copy-on-write" principle, that is, unless the occurrence Write operations, variables that point to the same address, or objects that are not copied, such as the following code:

$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 instead point to the same piece of memory, which is the difference between PHP and C, do not need to write $b=& $a to represent the $b point to $ A memory, Zend has already helped you to make references, and Zend will be very intelligent to help you decide when to deal with this and when not to do so.

If you continue to write the following code, add a function, pass the parameter by reference, and print the output array size.

Function PrintArray (& $arr)//reference delivery
{
Print (count ($arr));

}
PrintArray ($a);

In the above code, we pass the $ A array into the PrintArray () function by reference, and the Zend engine will think that PrintArray () may cause a change to $ A, which will automatically produce a $ A copy of the data for $b and re-request a piece of memory for storage. This is the "copy-on-write" concept mentioned earlier.

If we change the code above to the following:

function PrintArray ($arr)//value Pass
{
Print (count ($arr));
}
PrintArray ($a);

The above code passes a $ A value directly into PrintArray () and there is no reference pass at this time, so there is no write-time copy.

You can test the execution efficiency of the two lines of code above, such as adding a loop 1000 times outside to see how time is running, and the result will let you know that incorrect use of the reference will result in a decrease in performance by more than 30%.

Self-understanding: According to the value of the word is independent of the parameters within the function, equivalent to the role of local variables, and according to the address (reference) is related to the parameters within the function, equivalent to the role of global variables. In terms of performance, look at the above analysis is enough.

http://www.bkjia.com/PHPjc/965027.html www.bkjia.com true http://www.bkjia.com/PHPjc/965027.html techarticle PHP Reference () using a detailed, PHP reference to the beginner PHP reference to the Official document: 1. What is the reference: http://www.php.net/manual/zh/language.references.whatare.php 2. What the reference does: http: ...

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