To manipulate an outside variable within a function, you must define the variable outside of the function and then either pass it to the function as an argument or use global to access it. If you pass it as an argument and wish to be able to modify it directly, you must pass it by reference, which means you put a & before the name of the variable. Like so:
Code:
<?
$a = 0;
// global method
function add_one() {
global $a;
$a++;
}
add_one();
echo $a;
// this should output "1"
function times_two(&$var) {
$var *= 2;
}
// pass-by-reference
times_two($a);
echo $a;
// this should output 2
?>
(I just ran this and I'm amazed to find that it actually works -- I've never actually used references before.)
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.