In documentation i see how we set 2 &
, why?
And can say me please what difference beetween
this 1:
function &func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = func();
echo "var1:", $var1; // 1
and this 2:
function func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = func();
echo "var1:", $var1; // 1
Or alternative variant
this 1:
function &func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = &func();
echo "var1:", $var1; // 1
and this 2:
function func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = &func();
echo "var1:", $var1; // 1
There is only a difference between the first this 2
and the second this 1
. All others are wrongly tried return by reference
.
The second this 2
even throws a PHP notice ( Notice: Only variables should be assigned by reference in ... on line ...
).
The difference is that the first this 2
returns by value while the second this 1
returns by reference. Since it is a reference, the variable can be changed outside the function.
function &func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = &func();
echo "var1:", $var1; // 1
$var1 = 10;
$var1 = &func();
echo "\nvar1:", $var1; // 11
evals for all snippets (with second function call):
1st this 1: https://3v4l.org/p6erT
1st this 2: https://3v4l.org/9OcaC
2nd this 1: https://3v4l.org/uJHSF
2nd this 2: https://3v4l.org/qJ3qO
See also the PHP manual: https://secure.php.net/manual/en/language.references.return.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.