How can the use of global variables be avoided in PHP scripts?
Global variables can be avoided in PHP scripts by using functions to encapsulate variables within their scope. By passing variables as parameters to functions or using return values to retrieve data, you can avoid the need for global variables. This helps improve code readability, maintainability, and reduces the risk of variable conflicts.
function calculateSum($num1, $num2) {
return $num1 + $num2;
}
$number1 = 10;
$number2 = 20;
$result = calculateSum($number1, $number2);
echo "The sum of $number1 and $number2 is: $result";