How can passing parameters to functions instead of relying on global variables improve code readability and maintainability?
Passing parameters to functions instead of relying on global variables improves code readability and maintainability by making the function's dependencies explicit. This approach makes it easier to understand the function's behavior and reduces the risk of unintended side effects. It also promotes code reusability and testability as functions become more self-contained and predictable.
// Using parameters instead of global variables
function calculateTotal($items) {
$total = 0;
foreach ($items as $item) {
$total += $item;
}
return $total;
}
$items = [10, 20, 30];
$total = calculateTotal($items);
echo "Total: $total";