Not sure if this is a contrived example or not, but in this case (as in most cases) it would be extremely bad form to use global
. Why not just return the results and assign the return value?
$test = 1;
function increment($val) {
return $val + 1;
}
$test = increment($test);
echo $test;
This way, if you ever need to increment any other variable besides $test
, you're done already.
If you need to change multiple values and have them returned, you can return an array and use PHP's list
to easily extract the contents:
function incrementMany($val1, $val2) {
return array( $val1 + 1, $val2 + 1);
}
$test1 = 1;
$test2 = 2;
list($test1, $test2) = incrementMany($test1, $test2);
echo $test1 . ', ' . $test2;
You can use func_get_args
to also accept a dynamic number of arguments and return a dynamic number of results as well.