PHP Reference (&) detailed and Precautions

Source: Internet
Author: User
Tags add anonymous functions variables php class php and variable zend

References to PHP (including & symbols before a variable or function or object or object method)

References in PHP mean that different names 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's reference allows you to use two variables to point to the same content.

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

2. Reference pass of function (call to address )

I'm not going to say any more, I'll just give you the following code:

<?php
function Test (& $a) {
	$a = $a +;
}
$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 $a value in the function, you can change the $b value.
echo "<br>";
Echo $b; Output
?>

Note that here test (1); Then you will make a mistake and think for yourself.

Attention:

"Test ($b) above; "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:

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

First look at the code:

<?php
function &test () {
	static $b = 0;//declares a static 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 a value of $b of 3
$a = 5;
$a = Test (); This statement will output a value of $b 6
?>

The following explains:

In this way $a =test (); The result is not the return of the function reference, which is no different from the normal function call, as the reason: this is the PHP rule.

PHP rules through $a=&test (); The way to get the function is to return the reference, as to what is the reference to return it (PHP manual says: Reference return is used when you want to use a function to find the reference should be bound to which variable above.) This nonsense, I did not read for half a day.

Use the example above to explain:

Call the function $a = Test () just assign the value of the function to $a, and $a make any changes that do not affect the $b in the function, and call the function by $a = &test (), which is the function of the return $b the memory address of the $b variable and the $ 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.

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

Another example of a PHP official:

<?php//This are the way how do
we use 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 = ' Are ';
$aa->out ();
$d = ' you ';
$aa->out ();

The output is "hihowareyou"
?>

4. References to Objects

<?php
Class A {
	var $abc = "abc";
}
$b = new A;
$c = $b;
Echo $b->abc; Here the output ABC
echo $c->abc;//Here outputs 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 $b above = 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 may want to create a copy of the object and expect the changes of the original object to not affect 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 $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 will generally be changed to the 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:

<?php class Foo {protected $name;
	function __construct ($str) {$this->name = $str; The function __tostring () {return ' I name is '. $this->name. ' and I live in '. __class__. '".' . "
	";
	function SetName ($str) {$this->name = $str;

	} class Masterone {protected $foo;
	function __construct ($f) {$this->foo = $f; function __tostring () {return ' Master: '. __class__. ' foo: '. $this->foo.
	" ";
	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.
	" ";
	function Setfooname ($str) {$this->foo->setname ($STR);

} $bar = new foo (' Bar ');
Print ("");
Print ("Only Created $bar and printing $bar");

Print ($bar);
Print ("");
Print ("Now $baz are referenced to $bar and printing $bar and $baz");
$baz = & $bar;

Print ($bar); PriNT ("");
Print ("Now creating Masterone and two with passing $bar to both constructors");
$m 1 = new Masterone ($bar);
$m 2 = new Mastertwo ($bar);
Print ($m 1);

Print ($m 2);
Print ("");
Print ("Now changing value of $bar and printing $bar and $baz");
$bar->setname (' Baz ');
Print ($bar);

Print ($baz);
Print ("");
Print ("Now printing again Masterone and two");
Print ($m 1);

Print ($m 2);
Print ("");
Print ("Now changing Mastertwo ' s foo name and printing again Masterone and two");
$m 2->setfooname (' mastertwo\ ' Foo ');
Print ($m 1);

Print ($m 2);
Print ("Also Printing $bar and $baz");
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 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:

$bar = new Foo (' Bar ');
$m 1 = new Masterone ($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. $m 1 or $M2, any action on $bar affects the related values of the external object instance $bar.
    2. The $bar of external object instances can also affect reference-related values for $bar within $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:

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 clear it manually, the individual suggested that the "&", and then $var = NULL to clear the way. 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:

<?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 $GLOBALS avoid this by using arrays.

Example reference global variables within a function

<?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 global context
	}
}

global_references (false);
echo "VAR2 is set to ' $var 2 '
";//Var2 be set to '
global_references (true);
echo "VAR2 is set to ' $var 2 '
";//Var2 be set to ' Example variable '
?>

Take global $var as a shorthand for $var = & $GLOBALS [' var ']; 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

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

<?php
$a = "EFG";
? >

Because the data of the memory pointed to by $a and $b is to be written again, at this point Zend Core will automatically judge, automatically for $b production of a $a copy of the data, reapply a memory for storage PHP reference (that is, in variables or functions, objects, etc. before adding & symbol) is a high-level topic, Novice more attention, the right to understand the PHP reference is important, the 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. All others need to use * to define, and PHP for the address (like a pointer) function is not implemented by the user, is implemented by the Zend Core, PHP referenced by the "write-time copy" principle, Is that unless a write occurs, a variable or object that points to the same address is 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 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.

Function PrintArray (& $arr) {//reference pass
	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:

function PrintArray ($arr) {//value pass
	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.

Articles that you may be interested in

    • PHP Security Programming considerations
    • Site Space Security Considerations
    • Summary of methods for using Curl post submission data and get access to Web page data in PHP
    • Use return in PHP recursive function should be noted
    • PHP uses Array_flip to implement array key exchange to remove duplicate value of array
    • PHP uses regular filters for various labels, spaces, line breaks, code
    • Summary of usage of thinkphp built-in template engine
    • PHP uses Curl functions to implement multi-threaded crawl Web pages and download files


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.