HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Variable Scope

Scope defines the visibility and lifetime of a variable within your script. In PHP, variables have different access rules depending on where they are declared. Understanding these rules is vital for preventing data conflicts and "undefined variable" errors.


1. Local Scope

Variables declared inside a function are local to that function. They are created when the function starts and destroyed as soon as the function ends.

<?php
    function myTest() {
        $x = 5; // Local scope
        echo "Variable x inside function is: $x";
    }
    myTest();

    // echo $x; // This would result in an error!
?>

2. Global Scope

A variable declared outside a function has a global scope and can only be accessed outside a function.

Using the global Keyword

To access a global variable from within a function, you must use the global keyword.

<?php
    $x = 10;
    $y = 20;

    function myTest() {
        global $x, $y;
        $y = $x + $y;
    }

    myTest();
    echo $y; // Outputs: 30
?>

The $GLOBALS Superglobal

PHP also stores all global variables in an associative array called $GLOBALS[index]. The index is the name of the variable.

<?php
    $x = 5;
    $y = 10;

    function myTest() {
        $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
    }

    myTest();
    echo $y; // Outputs: 15
?>

3. Static Scope

Normally, when a function is completed, all of its local variables are deleted. However, sometimes we want a local variable NOT to be deleted. To do this, use the static keyword.

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

    myCounter(); // 0
    myCounter(); // 1
    myCounter(); // 2
?>
Visibility Tip: Variables declared in one file are accessible in another file only if that file is included using include or require.
Pro Tip: Minimizing the use of global variables is a hallmark of good programming. Use function arguments and return values to pass data instead whenever possible.

Key Points to Remember

  • Local variables only exist inside the function where they are born.
  • Global variables exist outside functions but need the global keyword to be used inside.
  • The $GLOBALS array is a built-in way to access all global data.
  • Static variables remember their value even after the function has finished running.
  • Static variables are only initialized once (the first time the function is called).