PHP Variables Scope

In PHP, variable scope refers to the visibility of a variable within different parts of a PHP script. The scope of a variable determines where in the code the variable can be accessed, and where it cannot.

There are two types of variable scope in PHP: global and local.

Global Variables: Global variables are declared outside of any function, which means they can be accessed from anywhere within the script, including within functions.

Example:

<?php
// Declare a global variable
$name = "John Doe";
// Define a function that uses the global variable
function greet() {
    global $name;
    echo "Hello, " . $name . "!";
}
// Call the function
greet(); // Output: Hello, John Doe!
?>

In this example, we declare a global variable called $name and assign the value “John Doe” to it. We then define a function called greet() that uses the global variable using the global keyword to make it available within the function. We then call the function, which outputs “Hello, John Doe!”.

Local Variables: Local variables are declared inside a function, which means they can only be accessed within that function.

Example:

<?php
// Define a function that declares a local variable
function greet() {
    $name = "John Doe";
    echo "Hello, " . $name . "!";
}
// Call the function
greet(); // Output: Hello, John Doe!
// Attempt to output the value of the local variable outside the function
echo $name; // Throws an "Undefined variable" error
?>

In this example, we define a function called greet() that declares a local variable called $name and assigns the value “John Doe” to it. We then call the function, which outputs “Hello, John Doe!”. We then attempt to output the value of the local variable outside the function, which throws an “Undefined variable” error because the variable is not defined outside the function.

Variables can also have static scope, which means their value is preserved between function calls:

<?php
// Define a function that uses a static variable
function increment() {
    static $count = 0;
    $count++;
    echo "Count: " . $count . "<br>";
}
// Call the function multiple times
increment(); // Output: Count: 1
increment(); // Output: Count: 2
increment(); // Output: Count: 3
?>

In this example, we define a function called increment() that uses a static variable called $count. The static variable is initialized to 0 the first time the function is called, and its value is preserved between subsequent calls. We then call the function multiple times, which outputs “Count: 1”, “Count: 2”, and “Count: 3” respectively.