Understand PHP return references and local static variables, and php local static variables
Read the manual first
============
To return a reference from a function, you must use the reference operator when declaring the function and assigning the return value to a variable &:
Copy codeThe Code is as follows:
<? Php
Function & returns_reference ()
{
$ Someref = 0;
Return $ someref;
}
$ Newref = & returns_reference (); // equivalent to $ newref = & $ someref;
?>
For more information about references, see references.
Let's take a look at a lot of examples of registration modes that open-source code prefers.
Copy codeThe Code is as follows:
Class {}
Class B {}
Function & aa ($ name)
{
Static $ class = array (); // The partial static variable does not disappear with the execution of the method, but ends the lifecycle only when the entire source program ends.
If (! $ Class [$ name]) // so the Declaration/initialization statement here takes effect only when it is declared for the first time.
{// When this method is called later, the static variable does not reinitialize the value.
$ Class [$ name] = new $ name ();
}
Return $ class [$ name];
}
$ A = & aa ('A ');
$ B = & aa ('B ');
$ A2 = & aa ('A ');
$ B2 = & aa ('B ');
Echo $ a ===$ a2? '$ A and $ a2 are the same instantiated objects <br/> ':'';
Echo $ B ===$ b2? '$ B and $ b2 are the same instantiated objects ':'';