Variables and Scope
Pageturn keeps a shop-wide discount in a variable at the top of the file. You write a function to work out a sale price, use the discount inside it, and get a warning plus the wrong answer. Nothing is misspelled. The function simply cannot see the variable, and that is PHP's scope rule at work.
The rule
A function sees only its own variables — pass in what it needs.
Variables start with $, then a letter or underscore: $title, $in_stock, $_tmp. They need no declaration. Assigning a value creates the variable, and it can hold any type later.
<?php
$discount = 0.10; // global scope: the top level of the file
function salePrice($price) {
return $price - $price * $discount; // Warning: Undefined variable $discount
}
function salePriceFixed($price, $discount) {
return $price - $price * $discount; // uses the parameter
}
echo salePriceFixed(9.99, $discount); // 8.991PHP has three scopes you meet early:
- Global: variables made at the top level of a script.
- Local: variables made inside a function, including its parameters. They vanish when the function returns.
- Static: a local variable marked
statickeeps its value between calls.
function nextOrderNumber() {
static $n = 0; // set to 0 only the first time
$n++;
return $n;
}
echo nextOrderNumber(); // 1
echo nextOrderNumber(); // 2Unlike many languages, PHP does not let functions read globals automatically. You can reach in with global $discount; or $GLOBALS['discount'], but that hides a dependency. Passing a parameter says clearly what the function uses.
The shortcut
For every variable inside a function, trace it to where it was born: a parameter, an assignment inside this function, or a static line. If it was born outside, the function does not have it.
Find the variable
Inside
salePrice, the code reads$discount.
Drills
Answer fast — trust the rule.
Which is a valid PHP variable name?
A function reads $discount, which was set only at the top level of the file. What happens?
What does the third call to nextOrderNumber() return?
What is the clearest way to give a function access to a value from outside it?
Remember
- A function sees only its own variables: pass in what it needs.
- Shortcut: trace each variable to its birth — parameter, local assignment or
static. - Trap: expecting globals to be visible inside functions, as they are in JavaScript or Python.
