agyanadda@gmail.com

PHP Variable Scope

Functions 1 min read Updated Dec 1, 2026 Topic 16 of 36

Scope decides where a variable can be used.

Local scope

Variables created inside a function exist only inside it. Also, a function cannot see variables from outside (unlike JavaScript).

$site = 'AgyanAdda';
function show() {
    echo $site; // Warning: undefined variable
}

Solutions

  1. Pass it as a parameter (best): function show(string $site)
  2. global $site; inside the function (avoid — makes code hard to test)
  3. For closures: function () use ($site) { ... } or arrow functions, which capture outer variables automatically

static variables

Keep their value between calls:

function counter() {
    static $count = 0;
    return ++$count;
}

Pass by reference

Add & to let a function change the original variable: function addBonus(array &$marks).

Example

Example — Scope, static and reference PHP
<?php
$siteName = 'AgyanAdda';

function welcome(string $site): string
{
    $message = "Welcome to $site"; // local variable
    return $message;
}
echo welcome($siteName) . '<br>';

function visitCounter(): int
{
    static $visits = 0;
    return ++$visits;
}
visitCounter();
visitCounter();
echo 'Visits: ' . visitCounter() . '<br>';

function addGrace(array &$marks, int $grace): void
{
    foreach ($marks as &$m) {
        $m = min(100, $m + $grace);
    }
}
$marks = [30, 55, 98];
addGrace($marks, 5);
echo 'After grace: ' . implode(', ', $marks) . '<br>';

$rate = 18;
$withGst = fn($price) => $price + $price * $rate / 100; // arrow fn sees $rate
echo 'With GST: ' . $withGst(100);

Output: Welcome to AgyanAdda / Visits: 3 / After grace: 35, 60, 100 / With GST: 118

Test Yourself With Exercises

Exercise 1 Multiple Choice

Can a PHP function read a variable created outside it without passing it in?

Exercise 2 True / False

A static variable keeps its value between function calls.

Exercise 3 Fill in the Blank

The ___ sign before a parameter passes it by reference.

Frequently Asked Questions

Any function could change the variable, which causes hard-to-find bugs. Passing values as parameters keeps functions predictable.