Skip to main content

PHP Variables Scope

You can declare a PHP variable anywhere in a script, but that doesn't mean you can use it everywhere. The part of the script where a variable is available is called its scope, and there are three kinds: local, global and static.


Global and Local Scope

Where you declare a variable decides its scope. Declared outside a function, it has global scope and is out of reach inside functions. Declared inside a function, it has local scope and exists only for that function.

Global scope variable

$x is created outside myTest(), so the function can't see it and prints no value. Only the echo outside the function shows 5:

Prompt
Write a PHP script that declares a variable $x with value 5 outside a function called myTest. Inside the function, try to echo $x. Then call the function. This will show that a global variable cannot be accessed inside a function.
Output: PHP script

Local scope variable

This time $x is created inside myTest(), so only the function's own echo shows 5. The line outside the function has nothing to print:

Prompt
Write a PHP script with a function called myTest that declares a local variable $x with value 5 and echoes it. After calling the function, try to echo $x outside the function. This will show that a local variable cannot be accessed outside a function.
Output: PHP script

The PHP global Keyword

A function can still reach a global variable if you ask for it. Inside the function, write the global keyword before the variable names.

Using the global keyword

With global $x, $y; the function works directly on the outer variables, so the new value of $y is still there when the function ends:

Prompt
Write a PHP script that declares two global variables $x = 5 and $y = 10. Create a function called myTest that uses the global keyword to access $x and $y, and stores their sum in $y. Call the function and echo $y.
Output: PHP script

Using the $GLOBALS array

PHP also keeps every global variable in an array named $GLOBALS[index]. A function can read and change them through that array, as this code does:

Prompt
Write a PHP script that declares two global variables $x = 5 and $y = 10. Create a function called myTest that uses the $GLOBALS array to access $x and $y, and stores their sum in $GLOBALS['y']. Call the function and echo $y.
Output: PHP script

The PHP static Keyword

A function's variables normally vanish once it finishes running. Sometimes, though, you want a local variable to survive until the next call because you still need its value. Just add the static keyword the first time you declare it:

Using the static keyword

Because $x is static, each call picks up where the last one left off, so the output counts 0, 1, 2:

Prompt
Write a PHP script with a function called myTest that declares a static variable $x with value 0, echoes $x, and then increments $x. Call the function three times to show the static variable retains its value between calls.
Output: PHP script