How can PHP functions be optimized to avoid using the "global" keyword, as suggested in the responses?
Using the "global" keyword in PHP functions can lead to code that is difficult to maintain and test. To avoid this, you can pass variables as parameters to the function instead of relying on the global scope. This makes the function more self-contained and easier to understand.
// Avoid using global keyword by passing variables as parameters
function calculateTotal($itemPrices) {
$total = 0;
foreach ($itemPrices as $price) {
$total += $price;
}
return $total;
}
$itemPrices = [10, 20, 30];
$total = calculateTotal($itemPrices);
echo "Total: " . $total;
Keywords
Related Questions
- What are the best practices for structuring a SQL query to count values in a MySQL database based on specific conditions?
- What are the best practices for handling form validation and error messages in PHP scripts?
- What is the function in PHP to retrieve the IP address of a guestbook entry author and how can it be stored in a database?