php中的引用传值

WBOY
Release: 2016-06-23 13:24:09
Original
1265 people have browsed it

一、简单数据类型的的赋值为值传递,函数返回值赋值也是值传递。且php中引用采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或者对象是不会被拷贝的。

通俗的讲 

    1:如果有下面的代码 

$a="ABC"; $b=$a;
Copy after login

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

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

$a="EFG";
Copy after login

由于$a与$b所指向的内存的数据要重新写一次了,此时Zend核心会自动判断 自动为$b生产一个$a的数据拷贝,重新申请一块内存进行存储

二、对象的赋值是引用传递,在方法定义和调用前都加上&操作符也会作为引用传递:

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

三、当用 global关键字声明一个变量时,实际上建立了一个到全局变量的引用。也就是说下面两行的结果是相同的:

global $val;$var =& $GLOBALS["var"];/*当用unset($val)取消引用时,只是断开了变量名$var和 变量内容 之间的绑定,并不会销毁全局变量$GLOBALS["var"]*/
Copy after login


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!