Skip to content
PHP Logo

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.

php
function calculateTotal($price, $quantity) {
    $total = $price * $quantity;
    return $total;
}

$price = 10;
$quantity = 5;
echo calculateTotal($price, $quantity); // Output: 50