PHP reference (&) detailed explanation and precautions_PHP tutorial

WBOY
Release: 2016-07-13 10:17:22
Original
894 people have browsed it

php reference (&) detailed explanation and precautions

PHP reference (that is, in variable or function or Object or Object method etc. preceded by & symbols)

Quotation 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 reference

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

<?
$a = "ABC";
$b = &$a;
echo $a; //这里输出:ABC
echo $b; //这里输出:ABC
$b = "EFG";
echo $a; //这里$a的值变为EFG 所以输出EFG
echo $b; //这里输出EFG
?>
Copy after login

2. Function's pass by reference (call by address)

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

<?php
function test(&$a) {
	$a = $a + 100;
}
$b = 1;
echo $b; //输出1
test($b); //这里$b传递给函数的其实是$b的变量内容所处的内存地址,通过在函数里改变$a的值,就可以改变$b的值了。
echo "<br>";
echo $b; //输出101
?>
Copy after login

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 pass parameters by reference, you need the & symbol, as follows The code is shown:

<?php
function a(&$b) {
	$b++;
}
$c = 0;
call_user_func_array('a', array(&$c));
echo $c; //输出 1
?>
Copy after login

3. The reference of the function returns

Look at the code first:

<?php
function &test() {
	static $b = 0;//申明一个静态变量
	$b = $b + 1;
	echo $b;
	return $b;
}

$a = test(); //这条语句会输出 $b的值 为1
$a = 5;
$a = test(); //这条语句会输出 $b的值 为2

$a = &test(); //这条语句会输出 $b的值 为3
$a = 5;
$a = test(); //这条语句会输出 $b的值 为6
?>
Copy after login

Explanation below:

In this way, $a=test(); actually does not get a function reference return, which is no different from an ordinary function call. As for the reason: this is a PHP regulation.

PHP stipulates that what is obtained through $a=&test(); is the reference return of the function. As for what is the reference return (the PHP manual says: the reference return is used when you want to use the function to find the reference, it should be bound to Which variable is above?) This nonsense made me unable to understand it for a long time.

Using the above example to explain:

$a = test() When calling a function, it just assigns the value of the function to $a, and any changes to $a will not affect $b in the function, and by $a = &test() When calling a function, its function is to point the memory address of the $b variable in return $b and the memory address of the $a variable to the same place, which generates Equivalent to this effect ($a = &$b;) So changing the value of $a also changes the value of $b, so after executing

$a = &test();
$a = 5;
Copy after login

Afterwards, the value of $b becomes 5.

Static variables are used here to let everyone understand the reference return of the function. In fact, the reference return of the function is mostly used in objects.

Attached is an official PHP example:

<?php
// 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"
?>
Copy after login

4. Object reference

<?php
class a {
	var $abc = "ABC";
}
$b = new a;
$c = $b;
echo $b->abc; // 这里输出ABC
echo $c->abc; // 这里输出ABC
$b->abc="DEF";
echo $c->abc; // 这里输出DEF
?>
Copy after login

The above code is the effect of running in PHP5.

Object assignment in PHP5 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 the object by reference, but sometimes you may want to create a A copy of the object, and hopes that changes to the original object will not affect the copy. For such purposes, 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, such as: $b = new a, where new a produces an anonymous a object instance, and $b at this time is a copy of this anonymous object. Similarly, $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:

<?php
class foo {
	protected $name;

	function __construct($str) {
		$this->name = $str;
	}

	function __toString() {
		return 'my 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 is referenced to $bar and printing $bar and $baz ");
$baz = &$bar;
print($bar);

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

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($m1);
print($m2);

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

print("Also printing $bar and $baz");
print($bar);
print($baz);
?>
Copy after login

Output:

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

上个例子解析:

$bar = new foo('bar');
$m1 = new MasterOne($bar);
Copy after login

实例对象$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;
	}
}
Copy after login

5.引用的作用

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

6.取消引用

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

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

不会 unset $b,只是 $a。

7.global 引用

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

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

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

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

Example  在函数内引用全局变量

<?php
$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'
"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'
"; // var2 is set to 'Example variable'
?>
Copy after login

global $var; 当成是 $var = &$GLOBALS['var']; 的简写。从而将其它引用赋给 $var 只改变了本地变量的引用。

8.$this

在一个对象的方法中,$this 永远是调用它的对象的引用。

//下面再来个小插曲

PHP中对于地址的指向(类似指针)功能不是由用户自己来实现的,是由Zend核心实现的,PHP中引用采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或者对象是不会被拷贝的。

通俗的讲

1:如果有下面的代码

<?
$a = "ABC";
$b = &$a;
?>
Copy after login

其实此时 $a与$b都是指向同一内存地址 而并不是$a与$b占用不同的内存

2:如果在上面的代码基础上再加上如下代码

<?php
$a = "EFG";
?>
Copy after login

由于$a与$b所指向的内存的数据要重新写一次了,此时Zend核心会自动判断,自动为$b生产一个$a的数据拷贝,重新申请一块内存进行存储PHP的引用(就是在变量或者函数、对象等前面加上&符号)是个高级话题,新手多注意,正确的理解PHP的引用很重要,对性能有较大影响,而且理解错误可能导致程序错误!

很多人误解PHP中的引用跟C当中的指针一样,事实上并非如此,而且很大差别。C语言中的指针除了在数组传递过程中不用显式申明外,其他都需要使用*进行定 义,而PHP中对于地址的指向(类似指针)功能不是由用户自己来实现的,是由Zend核心实现的,PHP中引用采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或者对象是不会被拷贝的,比如下面的代码:

$a = array('a','c'...'n');
$b = $a;
Copy after login

如果程序仅执行到这里,$a和$b是相同的,但是并没有像C那样,$a和$b占用不同的内存空间,而是指向了同一块内存,这就是PHP和C的差别,并不需要写成$b=&$a才表示$b指向$a的内存,zend就已经帮你实现了引用,并且zend会非常智能的帮你去判断什么时候该这样处理,什么时候不该这样处理。

如果在后面继续写如下代码,增加一个函数,通过引用的方式传递参数,并打印输出数组大小。

function printArray(&$arr) { //引用传递
	print(count($arr));
}
printArray($a);
Copy after login

上面的代码中,我们通过引用把$a数组传入printArray()函数,zend引擎会认为 printArray() 可能会导致对$a的改变,此时就会自动为$b生产一个$a的数据拷贝,重新申请一块内存进行存储。这就是前面提到的“写时拷贝”概念。

如果我们把上面的代码改成下面这样:

function printArray($arr) { // 值传递
	print(count($arr));
}
printArray($a);
Copy after login

上面的代码直接传递$a值到printArray()中,此时并不存在引用传递,所以没有出现写时拷贝。

大家可以测试一下上面两行代码的执行效率,比如外面加入一个循环1000次,看看运行的耗时,结果会让你知道不正确使用引用会导致性能下降30%以上。

自我理解:按传值的话是与函数内的参数无关,相当于局部变量的作用,而按传址(引用)的话却与函数内的参数有关,相当于全局变量的作用。而从性能方面来说,看上面分析就够。

您可能感兴趣的文章

  • php安全编程注意事项
  • 在php中分别使用curl的post提交数据的方法和get获取网页数据的方法总结
  • php递归函数中使用return需注意
  • 网站空间安全注意事项
  • ThinkPHP内置模板引擎的使用方法总结
  • php利用array_flip实现数组键值交换去除数组重复值
  • php利用正则过滤各种标签,空格,换行符的代码
  • PHP实现MVC开发得最简单的方法,模型的思考

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/892951.htmlTechArticlephp引用(amp; 符号) 在PHP 中引用的意思是:不同的名字访问同一个变量内容。 与C语言中的指针是有差别的。C语言中的指针里面存储的是变...
Related labels:
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!