Lesson 9 — Fundamentals

Functions

Functions bundle reusable logic under a name, and PHP supports default parameter values, type hints, and return type declarations to make them more predictable.

Defining a Function

A function is declared with the function keyword. Parameters can have default values, used when the caller doesn't provide that argument.

PHP — Functions with defaults and type hints
function calculateTotal(float $price, int $quantity, float $taxRate = 0.15): float {
    $subtotal = $price * $quantity;
    return $subtotal + ($subtotal * $taxRate);
}

echo calculateTotal(100, 3);        // uses default tax rate
echo calculateTotal(100, 3, 0.10);  // overrides the tax rate

Variable Scope

A variable declared inside a function is local to it by default and cannot be accessed outside. To use an outer variable inside a function, it must be passed in as a parameter (the recommended approach) or explicitly imported with global.

Common Mistakes

  • Expecting a variable declared inside a function to be visible outside it, without understanding PHP's function-level scope.
  • Placing required parameters after optional ones in a function's signature, which PHP does not allow.
  • Ignoring type hints and return types, losing an easy layer of built-in error checking.
  • Overusing global variables instead of passing values explicitly as parameters, which makes functions harder to test and reason about.

Professional Tip

Add type hints and return types to your functions wherever practical, e.g. function calculateTotal(float $price): float. PHP will raise a clear error if the wrong type is passed, catching bugs much earlier than they'd otherwise surface.

Your Turn

Write a function called formatCurrency that accepts a float and returns it formatted as a string with an 'R' prefix and two decimal places.

Mini Quiz

By default, can a variable declared inside a PHP function be accessed from outside that function?