Home > php教程 > php手册 > body text

PHP变量引用(&)、函数引用和对象引用

WBOY
Release: 2016-06-13 09:15:41
Original
1084 people have browsed it

PHP变量引用(&)、函数引用和对象引用

 1.变量的引用

PHP 的引用 两个变量的指针指向同一内存地址

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

 

3.函数的引用返回

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

下面解释下:
通过这种方式$a=test();得到的其实不是函数的引用返回,这跟普通的函数调用没有区别 至于原因: 这是php的规定
通过$a=&test()方式调用函数呢, 他的作用是 将return $b中的 $b变量的内存地址与$a变量的内存地址 指向了同一个地方
即产生了相当于这样的效果($a=&$b;) 所以改变$a的值 也同时改变了$b的值 所以在执行了

4.对象的引用(PHP5)

class foo {
  public $bar = 1;
}

$a = new foo;   //$a其实也是一个引用
$b = $a;        //拷贝引用 ($a)=($b)={id1}

$a->bar = 2;
echo "b->bar = $b->bar\n";

$b->bar = 3;
echo "a->bar = $a->bar\n";
//修改了b,但实际上是修改了a和b所引用的同一个对象
//并不会引发 Copy On Write 创建一个新对象b

$a = new foo;   //$a被修改为一个新的引用,$b没有改变
                //($a)={id2} ($b)={id1}
$a->bar = 4;
echo "b->bar = $b->bar\n";

$b = &$a;       //显式地使用引用,b成为“对象的引用”的引用
$a = new foo;   //($a)={id3} ($b)=&($a)=&{id3}
$a->bar = 5;
echo "b->bar = $b->bar\n"
//==output====
b->bar = 2
a->bar = 3
b->bar = 3
b->bar = 5
Copy after login
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 Recommendations
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!