MasterPHP.in
PHP Tutorial

Variable Scope in PHP


What is Variable Scope?

Variable scope refers to where in your code a variable can be accessed. Not every variable is available everywhere in a PHP script — depending on where and how it's declared, a variable might only exist inside a single function, or it might be available throughout your entire file. Understanding scope prevents a whole category of confusing bugs, especially the classic "why isn't this variable working inside my function?" problem that trips up almost every PHP beginner at some point.

PHP has three main types of variable scope: local, global, and static.


Local Scope

A variable declared inside a function only exists within that function. This is called local scope, and it's the default behavior for any variable created inside a function body.


php

<?php
function greetUser() {
    $message = "Welcome!";
    echo $message; // works fine here
}

greetUser(); // Welcome!

echo $message; // Error: Undefined variable $message

The variable $message only exists while greetUser() is running. Once the function finishes executing, that variable is gone, and trying to access it outside the function throws an error. This isolation is actually a good thing — it means functions don't accidentally interfere with each other's variables, even if they happen to use the same variable names.


php

<?php
function calculateTotal() {
    $result = 100;
    return $result;
}

function calculateDiscount() {
    $result = 20; // completely separate from the $result above
    return $result;
}

echo calculateTotal();    // 100
echo calculateDiscount(); // 20

Global Scope

A variable declared outside of any function exists in the global scope, meaning it's accessible anywhere in the main script — but importantly, not automatically inside functions. This is one of the most common sources of confusion for beginners coming from other languages.


php

<?php
$siteName = "MasterPHP";

function showSiteName() {
    echo $siteName; // Error: Undefined variable $siteName
}

showSiteName();

Even though $siteName is a global variable, PHP doesn't let functions see it by default. This is a deliberate design choice that keeps functions predictable and self-contained, since a function's behavior shouldn't quietly depend on variables defined somewhere else in the file.


Accessing Global Variables Inside a Function

If you genuinely need to access a global variable from inside a function, PHP provides the global keyword:


php

<?php
$siteName = "MasterPHP";

function showSiteName() {
    global $siteName;
    echo $siteName; // MasterPHP
}

showSiteName();

The global keyword tells PHP to look for $siteName in the global scope instead of treating it as a new local variable. It's worth using sparingly, though — leaning too heavily on global variables inside functions makes code harder to test and reason about, since the function's output now depends on external state rather than just its inputs.


The $GLOBALS Superglobal

PHP also provides a built-in array called $GLOBALS that gives access to all global variables from anywhere, including inside functions, without needing the global keyword:


php

<?php
$siteName = "MasterPHP";

function showSiteName() {
    echo $GLOBALS['siteName']; // MasterPHP
}

showSiteName();

$GLOBALS works similarly to global, but as an array, it can be useful in situations where you need to reference global variables dynamically.


Static Scope

Normally, a local variable is destroyed and recreated fresh every time a function is called. The static keyword changes this behavior, allowing a variable to retain its value between multiple calls to the same function.


php

<?php
function countVisits() {
    static $count = 0;
    $count++;
    echo $count . "\n";
}

countVisits(); // 1
countVisits(); // 2
countVisits(); // 3

Without static, $count would reset to 0 and print 1 every single time the function is called, since a normal local variable doesn't remember anything from a previous call. static is particularly useful for scenarios like counting how many times a function has run, or caching a value so expensive calculations aren't repeated unnecessarily.


Function Parameters and Scope

Function parameters behave like local variables — they only exist within the function they belong to, even though they receive their initial value from outside.


php

<?php
function applyDiscount($price) {
    $price = $price - ($price * 0.1);
    return $price;
}

$originalPrice = 500;
$finalPrice = applyDiscount($originalPrice);

echo $originalPrice; // 500 - unchanged
echo $finalPrice;    // 450

Notice that modifying $price inside the function has no effect on $originalPrice outside it. This is because PHP passes arguments by value by default — the function receives a copy, not a direct reference to the original variable.


Passing by Reference

In situations where you deliberately want a function to modify the original variable, PHP allows passing by reference using an ampersand (&):


php

<?php
function doubleValue(&$number) {
    $number = $number * 2;
}

$myNumber = 10;
doubleValue($myNumber);

echo $myNumber; // 20 - the original variable was changed

Passing by reference should be used deliberately and sparingly, since it breaks the predictability of a function only affecting its own local scope — a function like this can now change a variable's value outside itself, which needs to be clear from its name or documentation.


Scope Comparison at a Glance


Scope Type      Declared Where              Accessible Where
------------------------------------------------------------
Local            Inside a function           Only inside that
                                              same function
Global           Outside any function        Main script only,
                                              NOT inside functions
                                              (without `global`)
Static           Inside a function, using     Only inside that
                 the `static` keyword         function, but value
                                              persists between calls

Why Scope Matters for Writing Reliable Code

Understanding scope isn't just a technical detail — it directly affects how predictable and bug-free your code is. Functions that rely only on their own parameters and local variables (rather than reaching out to global state) are generally easier to test, debug, and reuse elsewhere in a project. This principle becomes even more important as you move toward object-oriented PHP and frameworks like Laravel, where managing scope and state cleanly is a core part of writing maintainable applications.


What's Next

With a solid understanding of where variables live and how long they last, the next lesson moves into functions themselves — how to define them, pass data in and out, and organize your code into clean, reusable blocks.

Frequently Asked Questions

By default, PHP functions have their own isolated local scope and cannot see variables from the global scope, even if those variables are declared in the same file. You need to explicitly use the global keyword or the $GLOBALS array to access them.
A global variable is declared outside any function and can be accessed inside functions using the global keyword. A static variable is declared inside a function but retains its value between multiple calls to that same function, rather than resetting each time.
By default, PHP passes variables to functions by value, meaning the function receives a copy and any changes made inside it don't affect the original variable. You can pass by reference instead by adding an ampersand (&) before the parameter name.
A static variable keeps its state contained within a single function, making it safer and more predictable than a global variable, which can potentially be modified from many different places in a script. Static variables are ideal for counters or caching within one specific function.
Relying heavily on global variables inside functions is generally discouraged because it makes functions harder to test and reason about independently. Passing values as function parameters and returning results explicitly is usually considered cleaner and more maintainable.

Share this tutorial