Home > Article > Backend Development > Return references and local static variables in PHP
This article mainly introduces the understanding of return references and local static variables in PHP. The general way to write return references is to add & before the method name. Local static variables are also very useful. I hope to be helpful.
Read the manual first
==========
Returning a reference from a function must be done both when the function is declared and when assigning the return value to a variable. Use the reference operator &:
<?php function &returns_reference() { $someref = 0; return $someref; } $newref = &returns_reference();//相当于 $newref = &$someref; ?>
For more information about references, see the explanation of references.
Let’s take a look at a single instance registration model that many open source codes like to use
class a{} class b{} function & aa($name) { static $class = array(); //局部静态变量 不随方法的执行结束而消失 而是坚持到整个源程序结束时才结束生命周期 if(!$class[$name]) //所以 此处的声明/初始化语句 只在首次声明时起作用 { //之后再调用此方法时, 静态变量不再重新初始化value $class[$name] = new $name(); } return $class[$name]; } $a = & aa('a'); $b = & aa('b'); $a2 = & aa('a'); $b2 = & aa('b'); echo $a === $a2 ? '$a和$a2是同一个实例化对象<br/>' : ''; echo $b === $b2 ? '$b和$b2是同一个实例化对象' : '';
Related recommendations:
php Detailed explanation of reference assignment
php Initialization example of static variables Detailed explanation
The above is the detailed content of Return references and local static variables in PHP. For more information, please follow other related articles on the PHP Chinese website!