How can one avoid issues with global variables when using recursive functions in PHP?
When using recursive functions in PHP, global variables can cause unexpected behavior or errors because each recursive call may modify the global variable's value. To avoid this issue, you can pass the variable as a parameter to the recursive function and update its value accordingly. This ensures that each recursive call operates on its own copy of the variable.
// Example of avoiding global variable issues in recursive functions
function recursiveFunction($n, $sum = 0) {
if ($n == 0) {
return $sum;
} else {
$sum += $n;
return recursiveFunction($n - 1, $sum);
}
}
$result = recursiveFunction(5);
echo $result; // Output: 15