How can the use of global variables in PHP scripts impact performance and readability?
Using global variables in PHP scripts can impact performance because they require additional memory allocation and can make it harder to track where variables are being modified throughout the script. Additionally, using global variables can make the code less readable and harder to maintain, as it may not be clear where a variable is being accessed or modified. To solve this issue, you can pass variables as parameters to functions or use object-oriented programming to encapsulate data within classes. This helps improve code organization, readability, and maintainability.
// Using parameters to pass variables to functions
function calculateTotal($items) {
$total = 0;
foreach ($items as $item) {
$total += $item;
}
return $total;
}
$items = [10, 20, 30];
$total = calculateTotal($items);
echo $total;