Im trying to change the value of a declared variable which is outside the function in use of a function
<?php
$test = 1;
function addtest() {
$test = $test + 1;
}
addtest();
echo $test;
?>
but it seems it couldn't. only variables declared as parameters in the function only work. is there a technique for this? thanks in advance
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.
Change the variable inside the function to a global -
function addtest() {
global $test;
$test = $test + 1;
}
There are a lot of caveats to using global variables -
your code will be harder to maintain over the long run because globals may have an undesired affect on future calculations where you might not be aware how the variable was manipulated.
if you refactor the code and the function goes away it will be detrimental because every instance of $test is tightly coupled to the code.
Here is a slight improvement and doesn't require global
-
$test = 1;
function addtest($variable) {
$newValue = $variable + 1;
return $newValue;
}
echo $test; // 1
$foo = addtest($test);
echo $foo; // 2
Now you haven't had to use a global and you have manipulated $test to your liking while assigning the new value to another variable.
Use the global
keyword.
<?php
$test = 1;
function addtest() {
global $test;
$test = $test + 1;
}
addtest();
echo $test; // 2
?>