What is the Scope of PHP Variables?

PHP variable scope defines where a variable can be accessed. Basically, there are two main types of scopes in PHP – Global and Local scope.

PHP Global and Local scoped variables

Variables declared outside of functions have a global scope and these global-scoped variables cannot be accessed inside a function.

Similarly, a variable declared inside a function has a local scope and the variable can be accessed only within that function.

PHP Global and Local scoped variables

PHP Super Global variables

PHP super global variables are a special type of variables that can be accessed from any scope.

Built-in Superglobal variables

$GLOBALS$_SERVER$_GET
$_POST$_FILES$_COOKIE
$_SESSION$_REQUEST$_ENV

Note: Constant variables are also like superglobals, you can access constants from anywhere in a script without regard to scope.


How to access global variables inside a Function?

We have learned that global variables cannot be accessed from inside a function. But there is a way to access global variables inside a function.

With the help of the global keyword or $GLOBALS (this is a superglobal variable), you can access global variables inside a Function. Let’s See –

<?php
$name = "John";

function show(){
    // global keyord example
    global $name;
    echo $name;
}

show();
John
<?php
$name = "Mark";
$age = 22;

function show(){
    echo $GLOBALS['name'];
    echo " => ";
    echo $GLOBALS['age'];
}

show();
Mark => 22

PHP static scope

There is one more scope that is called static. Let’s see how it works?

After a function is executed, all of its variables are usually deleted. Like the following –

<?php
function test(){
    $x = 0;
    $x = $x + 1;
    echo "$x ";
}

test();
test();
test();
1 1 1

But, if you want the local variable not to be deleted and its value to be remembered, then the static keyword helps to do that.

Use the static keyword before a the variable.

<?php
function test(){
    static $x = 0;
    $x = $x + 1;
    echo "$x ";
}

test(); // $x = 0 + 1
test(); // $x = 1 + 1
test(); // $x = 2 + 1
1 2 3