Return references and local static variables in PHP

*文
Release: 2023-03-18 17:30:02
Original
1085 people have browsed it

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;  
?>
Copy after login

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(&#39;a&#39;);  
$b = & aa(&#39;b&#39;);  
   
$a2 = & aa(&#39;a&#39;);  
$b2 = & aa(&#39;b&#39;);  
   
echo $a === $a2 ? &#39;$a和$a2是同一个实例化对象<br/>&#39; : &#39;&#39;;  
echo $b === $b2 ? &#39;$b和$b2是同一个实例化对象&#39; : &#39;&#39;;
Copy after login

Related recommendations:

php Quote (&) Usage

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!

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