PHP Variables & Scope

Learn how to define, manipulate, and understand the scope of variables in PHP.

📦 1. Create Different Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable. PHP is a loosely typed language, so we do not have to declare data types.

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;

echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>

🌍 2. Global Scope (Outside a Function)

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.

<?php
$x = 5; // global scope
    
function myTest() {
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";
} 
myTest();

echo "<p>Variable x outside function is: $x</p>";
?>

🏠 3. Local Scope (Inside a Function)

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.

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

// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>

🔑 4. The global Keyword

The global keyword is used to access a global variable from within a function.

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

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

myTest();  // run function
echo $y; // output the new value for variable $y (15)
?>

🌐 5. The $GLOBALS Array

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions.

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

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

myTest();
echo $y; // Output 15
?>

📌 6. The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We use the static keyword when first declaring the variable to achieve this.

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

myTest(); // Output 0
echo "<br>";
myTest(); // Output 1
echo "<br>";
myTest(); // Output 2
?>