예제 #1
0
파일: references.php 프로젝트: Keav/phpcms
}
$a = 10;
ref_test($a);
echo $a . "<br>";
// $a remains at 10 because the multiplication was local
// =======================================
echo "<hr>";
// =======================================
// reference variables in a function
function ref_test2(&$var)
{
    $var = $var * 2;
    echo $var . "<br>";
}
$a = 10;
ref_test2($a);
echo $a . "<br>";
// $a is now set to 20 because $a and $var have been set to each other
// Equivalent to using a global variable i.e. 'global $a;'
// but allows you to use different variable names within the function
// =======================================
echo "<hr>";
// =======================================
function &ref_return()
{
    global $a;
    $a = $a * 2;
    return $a;
}
$a = 10;
// Ordinarily a return returns the actual value e.g. 20, NOT the varialbe e.g. $a
예제 #2
0
</head>
<body>
<?php 
// now $var in this local scope will point to the same thing as $a
// in the global scope
// therefore when the value of $var inside gets changed it effects the
// memory bits that $a is pointing to... therefore when I echo $a
// afterwards it looks at the bits of memory that got changed by
// making a reference with $var inside the function!
function ref_test(&$var)
{
    $var = $var * 2;
}
$a = 10;
ref_test($a);
echo $a;
// note without the & at the $var in ref_test(&$var) then when
// I echo $a above would have been 10 instead of 20
echo "<hr>";
$b = 10;
// working with global seems a lot easier and straight forward
function ref_test2()
{
    global $b;
    $b = $b * 2;
}
ref_test2();
echo $b;
?>
</body>
</html>