How can passing parameters to functions be a more efficient alternative to using global variables in PHP scripts?
Passing parameters to functions in PHP scripts can be a more efficient alternative to using global variables because it limits the scope of variables to only where they are needed, reducing the risk of unintended changes or conflicts. By passing parameters, functions become more reusable and easier to test. This approach also promotes better code organization and readability.
// Using parameters instead of global variables
function calculateSum($num1, $num2) {
return $num1 + $num2;
}
$number1 = 5;
$number2 = 10;
$result = calculateSum($number1, $number2);
echo $result; // Output: 15
Keywords
Related Questions
- What are potential pitfalls when working with CDATA sections in XML files and how can they be addressed in PHP?
- What are the potential pitfalls of not properly handling MySQL result resources in PHP?
- In the provided PHP code, what improvements can be made to the logic of checking and handling the retrieved data from the database for better functionality and reliability?