What are the advantages and disadvantages of defining variables locally within a function in PHP?
When defining variables locally within a function in PHP, the advantages include encapsulation, avoiding variable name conflicts, and improved readability. However, the disadvantages are that the variable's scope is limited to that specific function and cannot be accessed outside of it.
function calculateTotal($price, $quantity) {
$total = $price * $quantity;
return $total;
}
$price = 10;
$quantity = 5;
echo calculateTotal($price, $quantity); // Output: 50
Related questions
-
cookies PHP setcookie
-
PHP SWFObject video
-
PHP string processing multiple spaces