PHP Variables Scope

In PHP, variables can be declared anywhere within the script. The scope of a variable defines the section of the script where the variable can be accessed or used.

Tutorials dojo strip

PHP has three main types of variable scope:

  1. Local
  2. Global
  3. Static




Global and Local Scope

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

Example: Variable with global scope

$motorcycle = "Harley"; // global scope

function showMotorcycle() {
    // using $motorcycle inside this function will generate an error
    echo "<p>Motorcycle inside function is: $motorcycle</p>";
}
showMotorcycle();

echo "<p>Motorcycle outside function is: $motorcycle</p>";

A variable declared within a function has a local scope and can only be accessed within that function.

Example: Variable with local scope

function showCar() {
    $car = "Toyota"; // local scope
    echo "<p>Car inside function is: $car</p>";
}
showCar();

// using $car outside the function will generate an error
echo "<p>Car outside function is: $car</p>";

Local variables with the same name can be used in different functions without conflict, as they are only recognized within their respective functions.




The global Keyword

The global keyword allows you to access a global variable from within a function. To achieve this, use the global keyword before the variable names inside the function.

Example: Using the global keyword

$brandA = "Nike";
$brandB = "Adidas";

function combineBrands() {
    global $brandA, $brandB;
    $brandB = $brandA . " and " . $brandB;
}

combineBrands();
echo $brandB; // outputs "Nike and Adidas"

PHP also stores all global variables in an array called $GLOBALS[index], where the index holds the variable name. This array can be accessed from within functions and used to modify global variables directly.

Example: Using $GLOBALS array

$brandA = "Levi's";
$brandB = "Wrangler";

function mixBrands() {
    $GLOBALS['brandB'] = $GLOBALS['brandA'] . " and " . $GLOBALS['brandB'];
}

mixBrands();
echo $brandB; // outputs "Levi's and Wrangler"




The static Keyword

Typically, when a function finishes executing, all its variables are deleted. However, sometimes we need a local variable to retain its value even after the function has completed. In such cases, we use the static keyword when declaring the variable.

Example: Using the static keyword

function trackMotorcycleSales() {
    static $sales = 0;
    echo $sales;
    $sales++;
}

trackMotorcycleSales(); // outputs 0
trackMotorcycleSales(); // outputs 1
trackMotorcycleSales(); // outputs 2

In this example, each time the function is called, the variable $sales retains the value it had from the previous call.

Tutorials dojo strip
Scroll to Top