Understand PHP return references and local static variables. Understanding PHP return references and local static variables this article mainly introduces PHP return references and local static variables. the general method of returning a reference is to add a method name before it, local static variables understand PHP return references and local static variables
This article mainly introduces PHP's return reference and local static variables. the general method of returning reference is to add the method name before &, and the local static variables are also very useful, for more information, see
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 &:
The code is as follows:
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.
The 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.
':'';
Echo $ B ===$ b2? '$ B and $ b2 are the same instantiated objects ':'';
This article mainly introduces PHP's return reference and local static variables. the general method of returning reference is to add the method name before the local static variables...