function variables

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.)
 
Back
Top