Home >Backend Development >PHP Tutorial >Understand PHP's return references and local static variables_PHP tutorial
This article mainly introduces understanding of PHP’s return references and local static variables. The general way to write a return reference is to add & before the method name. , local static variables are also very useful, friends in need can refer to it
Read the manual first
==========
To return a reference from a function, you must use the reference operator & both 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 citations, see the explanation of citations.
Let’s take a look at a single instance registration model that many open source codes like to use
The code is as follows:
class a{}
class b{}
Function & aa($name)
{
static $class = array(); //Local static variables do not disappear when the execution of the method ends, but persist until the end of the entire source program to end the life cycle
if(!$class[$name]) //So the declaration/initialization statement here only works when it is first declared
{ //When this method is called later, the static variable will no longer be re-initialized 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 object
' : '';
echo $b === $b2 ? '$b and $b2 are the same instantiated object' : '';