PHP Variable Scope

In PHP, the scope of a variable determines where it can be accessed. Variables in PHP can be categorized as:

  • ๐Ÿ”น Local Variables โ€“ Declared inside a function, accessible only within that function.
  • ๐Ÿ”น Global Variables โ€“ Declared outside functions, accessible anywhere using global or $GLOBALS.
  • ๐Ÿ”น Static Variables โ€“ Retains its value across multiple function calls.

๐Ÿ“ Example 1: Local Variables

Local variables are defined inside a function and cannot be accessed outside of it.

<?php
function localExample() {
    $message = "Hello from inside the function!";
    echo $message;
}

localExample();

// This will cause an error because $message is not available outside the function
// echo $message;
?>

Try It Now

Explanation:

  • $message is declared inside localExample().
  • It is only accessible within the function and will cause an error if accessed outside.

๐Ÿ“ Example 2: Global Variables

Global variables are defined outside functions but can be accessed inside functions using the global keyword or $GLOBALS array.

<?php
$siteName = "PHP Learning Hub";

function showSiteName() {
    global $siteName; // Using global keyword
    echo "Welcome to $siteName!";
}

showSiteName();
?>

Try It Now

Explanation:

  • $siteName is a global variable declared outside the function.
  • To access it inside showSiteName(), we use the global keyword.

๐Ÿ“ Example 3: Using $GLOBALS Array

Another way to access global variables inside functions is by using $GLOBALS.

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

function sumNumbers() {
    echo "Sum: " . ($GLOBALS['x'] + $GLOBALS['y']);
}

sumNumbers();
?>

Try It Now

Explanation:

  • $GLOBALS['x'] and $GLOBALS['y'] access the global variables.
  • This allows us to use them inside the function without the global keyword.

๐Ÿ“ Example 4: Static Variables

Static variables retain their value between function calls.

<?php
function countCalls() {
    static $count = 0; // Static variable
    $count++;
    echo "Function called $count times.<br>";
}

countCalls();
countCalls();
countCalls();
?>

Try It Now

Explanation:

  • $count is a static variable, so it keeps its value across function calls.
  • Each time the function runs, $count increments instead of resetting.

๐ŸŽฏ Key Takeaways

  • Local Variables: exist inside functions only.
  • Global Variables: exist outside functions but need global or $GLOBALS to be accessed inside.
  • Static Variables: retain their values between function calls.

๐Ÿ“ Practice Time!

Modify these examples and experiment with different values to understand how variable scope works in PHP!