Home  >  Article  >  php教程  >  了解PHP的返回引用和局部静态变量,php局部静态变量

了解PHP的返回引用和局部静态变量,php局部静态变量

WBOY
WBOYOriginal
2016-06-13 09:02:261114browse

了解PHP的返回引用和局部静态变量,php局部静态变量

先阅读手册
==========
从函数返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用操作符 & : 
复制代码 代码如下:
function &returns_reference() 

    $someref = 0; 
    return $someref; 

  
$newref = &returns_reference();//相当于 $newref = &$someref; 
?>

有关引用的更多信息, 请查看引用的解释。

在来看一段很多开源代码喜欢用的单例注册模式
复制代码 代码如下:
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是同一个实例化对象
' : ''; 
echo $b === $b2 ? '$b和$b2是同一个实例化对象' : '';

Statement:
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