Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial

WBOY
Release: 2016-07-13 10:04:36
Original
833 people have browsed it

Detailed explanation of the use of PHP quotation (&), php quotation

About & quotation for beginners in PHP

Official documentation:

1. What is the reference: http://www.php.net/manual/zh/language.references.whatare.php

2. What does the reference do: http://www.php.net/manual/zh/language.references.whatdo.php
3. Reference transfer: http://www.php.net/manual/zh/language .references.pass.php
4. Reference return: http://www.php.net/manual/zh/language.references.return.php

PHP reference (that is, adding an ampersand in front of a variable, function, object, etc.)

Reference in PHP means: different names access the same variable content.
It is different from pointers in C language. The pointer in C language stores the content of the variable and the address stored in the memory.

1. Variable references

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

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial
$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 EFG
is output echo $b;//EFG is output here
?> Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial


2. Function reference transfer (call by address)

I won’t go into details about the call by address. The code will be given directly below

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial function test(&$a)
{
$a=$a+100;
}
$b=1;
echo $b;// Output 1
test($b); //What $b is passed to the function here is actually the memory address where the variable content of $b is located. The value of $b can be changed by changing the value of $a in the function.
echo "
";
echo $b;//Output 101
?> Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial


It should be noted that if test(1); is used here, an error will occur. You have to think about the reason yourself.

Note:

Do not add the & symbol in front of $b in the above "test($b);", but in the function "call_user_func_array", if you want to quote the parameters, you need the & symbol, as follows The code is shown:

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial
function a(&$b){
$b++;
}
$c=0;

call_user_func_array('a',array( &$c));

echo $c;

//Output 1

?> Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial



3. Function reference returns

Look at the code first

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial function &test()
{
static $b=0;//Declare a static variable
$b=$b+1;
echo $b;
return $b;
}

$a=test();//This statement will output the value of $b as 1
$a=5;
$a=test ();//This statement will output the value of $b as 2

$a=&test();//This statement will output the value of $b as 3
$a=5;
$a=test();//This statement will output the value of $b as 6
?> Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial


The following explanation:
What you get in this way $a=test(); is not actually a function reference return, which is no different from an ordinary function call. As for the reason: This is the regulation of PHP
PHP stipulates that the reference return of the function is obtained through $a=&test();
As for what is a reference return (the PHP manual says: Reference return is used when you want to use a function to find a reference that should be bound When it is on which variable.) This nonsense made me unable to understand it for a long time.

Using the above example to explain, it is to call the function in the way of
$a=test(), which just assigns the value of the function. Just give $a, and any changes to $a will not affect $b
in the function. If the function is called through $a=&test(), its function is to return the $b variable in $b The memory address of the variable $a points to the same place
, which produces the same effect ($a=&$b;). So changing the value of $a also changes the value of $b. So After executing
$a=&test();
$a=5;
, the value of $b becomes 5

This is to let everyone understand the reference return of the function. When using static variables, in fact, function reference returns are mostly used in objects

Attached is an official php example:

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial This is the way how 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" Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial

4. Object reference

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial class a{
var $abc="ABC";
}
$b=new a;
$c=$b;
echo $b- >abc;//Output ABC
here echo $c->abc;//Output ABC
here $b->abc="DEF";
echo $c->abc; //Output DEF
?> here Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial

The above code is the effect of running in PHP5

In PHP5, object assignment is a reference process. In the above column, $b=new a; $c=$b; is actually equivalent to $b=new a; $c=&$b;
The default in PHP5 is to call objects by reference, but sometimes you may want to Create a copy of an object and hope that changes to the original object will not affect the copy. For this purpose, PHP5 defines a special method called __clone.

As of PHP 5, new automatically returns a reference, so using =& here is obsolete and produces an E_STRICT level message.

In php4, object assignment is a copy process,

For example: $b=new a, where new a produces an anonymous a object instance, and $b at this time is a copy of this anonymous object. In the same way, $c=$b is also a copy of the content of $b. Therefore, 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 official example:

In php5, you don’t need to add anything else to achieve the “object reference” function:

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial 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 $barn");
print( $bar );

print("n");
print("Now $baz is referenced to $bar and printing $bar and $bazn");
$baz =& $bar;
print( $bar );

print("n");
print("Now Creating MasterOne and Two and passing $bar to both constructorsn");
$m1 = new MasterOne( $bar );
$m2 = new MasterTwo( $bar );
print( $m1 );
print( $m2 );

print("n");
print("Now changing value of $bar and printing $bar and $bazn");
$bar->setName('baz');
print( $bar );
print( $baz );

print("n");
print("Now printing again MasterOne and Twon");
print( $m1 );
print( $m2 );

print("n");
print("Now changing MasterTwo's foo name and printing again MasterOne and Twon");
$m2->setFooName( 'MasterTwo's Foo' );
print( $m1 );
print( $m2 );

print("Also printing $bar and $bazn");
print( $bar );
print( $baz );
?> Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial

 

输出:

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial Only Created $bar and printing $bar
my name is "bar" and I live in "foo".

Now $baz is 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
my name is "baz" and I live in "foo".
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'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". Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial

 

上个例子解析:
$bar = new foo('bar');
$m1 = new MasterOne( $bar );
$m2 = new MasterTwo( $bar );
实例对象$m1与$m2中的$bar是对实例$bar的引用,而非拷贝,这是php5中,对象引用的特点,也就是说
1.$m1或$m2内部,任何对$bar的操作都会影响外部对象实例$bar的相关值。
2.外部对象实例$bar的改变也会影响$m1和$m2内部的$bar的引用相关值。

 

在php4中,要实现如上述的 用一个对象实例去当着另外一个对象的属性时,其等价代码(即引用调用)类似如下:

class foo{
   var $bar;
   function setBar(&$newBar){
      $this->bar =& newBar;
   }
}

 

 

 

 

5.引用的作用
     如果程序比较大,引用同一个对象的变量比较多,并且希望用完该对象后手工清除它,个人建议用 "&" 方式,然后用$var=null的方式清除. 其它时候还是用php5的默认方式吧. 另外, php5中对于大数组的传递,建议用 "&" 方式, 毕竟节省内存空间使用。


6.取消引用
当你 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如: 

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



不会 unset $b,只是 $a。 


7.global 引用
当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。也就是说和这样做是相同的: 

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


这意味着,例如,unset $var 不会 unset 全局变量。 

 

 

如果在一个函数内部给一个声明为 global 的变量赋于一个引用,该引用只在函数内部可见。可以通过使用 $GLOBALS 数组避免这一点。

Example Reference global variables within a function

Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial $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 to ''
global_references(true);
echo "var2 is set to '$var2'n"; // var2 is set to 'Example variable'
?> Detailed explanation of the use of PHP reference (&), php reference_PHP tutorial Think of global $var; as the abbreviation of $var =& $GLOBALS['var']; . Thus assigning other references to $var only changes the reference of the local variable.

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


//Here’s another little episode
The pointing (similar to pointer) function of the address in PHP is not implemented by the user himself, but is implemented by the Zend core, and is referenced in PHP. It is the principle of "copy-on-write", that is, unless a write operation occurs, variables or objects pointing to the same address will not be copied.

In layman terms
1: If there is the following code


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


In fact, $a and $b point to the same memory address at this time, rather than $a and $b occupying different memories

2: If you add The following code

$a="EFG";
?>


Since the data in the memory pointed to by $a and $b needs to be rewritten, at this time the Zend core will automatically determine and automatically produce a data copy of $a for $b, and re-apply for a piece of memory for storage

PHP references (that is, adding the ampersand in front of variables, functions, objects, etc.) is an advanced topic. Newbies should pay attention. It is very important to correctly understand PHP references, which has a great impact on performance, and misunderstandings may lead to Program error!

Many people misunderstand that references in PHP are the same as pointers in C. In fact, they are not, and they are very different. Except for the pointers in C language that do not need to be explicitly declared during the array transfer process, other points need to be defined using *. However, the pointer to address (similar to a pointer) function in PHP is not implemented by the user himself, but is implemented by the Zend core. Yes, the reference in PHP adopts the principle of "copy-on-write", that is, unless a write operation occurs, variables or objects pointing to the same address will not be 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 they do not occupy different memory spaces like C. Instead, they point to the same memory. This is php and c. The difference is that you don’t need to write $b=&$a to mean that $b points to the memory of $a. zend has already implemented the reference for you, and zend will be very smart to help you judge when to do this and when. It shouldn't be handled this way.

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

function printArray(&$arr) // Pass by reference
{
print(count($arr));

}
printArray($a);

In the above code, we pass the $a array into the printArray() function by reference. The zend engine will think that printArray() may cause changes to $a, and will automatically produce an $a for $b. Copy the data and re-apply a piece of memory for storage. This is the "copy-on-write" concept mentioned earlier.

If we change the above code to the following:

function printArray($arr) //Value transfer
{
print(count($arr));
}
printArray($a);

The above code directly passes the $a value to printArray(). There is no reference transfer at this time, so there is no copy-on-write.

You can test the execution efficiency of the above two lines of code. For example, add a loop outside 1000 times and see how long it takes to run. The results will let you know that incorrect use of references will cause performance to drop by more than 30%.

Self-understanding: When passing by value, it has nothing to do with the parameters in the function, which is equivalent to the role of local variables, but when passing by address (reference), it is related to the parameters within the function, which is equivalent to the role of global variables. From a performance perspective, it is enough to look at the above analysis. .

www.bkjia.comtruehttp: http: //www.php.net/manual/zh/language.references.whatare.php 2. What does the reference do: http:...
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!