PHP变量引用(&)、函数引用和对象引用
PHP变量引用(&)、函数引用和对象引用
1.变量的引用
PHP 的引用 两个变量的指针指向同一内存地址
$a="ABC"; $b =&$a; echo $a;//这里输出:ABC echo $b;//这里输出:ABC $b="EFG"; echo $a;//这里$a的值变为EFG 所以输出EFG echo $b;//这里输出EFG
2.函数的引用传递(传址调用)
function test(&$a) { $a=$a+100; } $b=1; echo $b;//输出1 test($b); //这里$b传递给函数的其实是$b的变量内容所处的内存地址,通过在函数里改变$a的值 就可以改变$b的值了 echo "<br>"; echo $b;//输出101 ?>
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
下面解释下:
通过这种方式$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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
