Skip to the workspace
Pebellslearn by building
Introduction to PHP  ›  Lesson

Variables and Scope

Variables and Scope 14 minScope determines where a PHP variable can be accessed. Functions have local variables and parameters, while explicit mechanisms expose outside values; static locals can retain a value between calls.

php / Variables and Scope

Explore each scene at your own pace.

01 · The rule

The rule

Variables and Scope

Scope determines where a PHP variable can be accessed. Functions have local variables and parameters, while explicit mechanisms expose outside values; static locals can retain a value between calls.

Trace names across global and function scopes and make external dependencies explicit.

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.991

PHP 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 static keeps its value between calls.
function nextOrderNumber() {
    static $n = 0;   // set to 0 only the first time
    $n++;
    return $n;
}
echo nextOrderNumber();   // 1
echo nextOrderNumber();   // 2

Unlike 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.