Variable Scope

Last updated on

The variable scope in PHP refers to the variables, functions, and classes that can be accessed within different parts of a PHP program.

In other words, the scope is like a rule that tells you where these bits of code can show up or be used in your program.

PHP has three main types of scopes: global, local, and static. Here is a quick explanation for each one.

  • Global scope refers to all variables that are made outside of functions and classes and that you can use anywhere in your program.
  • Local scopes are variables that are made inside the function or class and can only be used inside them. You will not be able to access the theme outside of the function or the class.
  • Static scopes are variables that are like local variables but with a memory. They remember their value every time you call the function.

Anyway, before getting started, let’s understand what scope is in PHP.

What does the word “scope” mean in PHP?

As I mentioned, “scope” refers to a variable that can be defined in one place and invoked as a reference in another place.

php scope

If you examine this puzzle, you will find four layers installed correctly, but there is an additional layer that will not work in its new position because it is invoked incorrectly or in the wrong position.

This process is called variable scope in PHP.

To understand what I mean, you have to change your way of thinking and transform the layers of this puzzle into variables and functions in PHP. Let me know if that works for you.

Defining a variable and invoking it as a reference in another place embodies the concept of scope in any programming language.

In the following sections, you will understand each type with an example. So let’s get started with the local scope.

Local Scope Variables

The local scope variable is one that is defined inside a code block, making it accessible only within the same block. For example:

function func() {
   $print = "Welcome to CodedTag tutorial.";
   echo $print;
}
func();

The $print variable is a local scope variable, meaning you can use it anywhere within the function. However, it is not possible to use a local variable as a reference outside the function since local variables can only be accessed within the same block where they are defined.

It cannot be used outside the block. For example:

function func() {
   $print = "Welcome to CodedTag tutorial."; 
}
func();

echo $print; // error here

In this example, I used the reference of the local variable $print outside the function. This will result in the following error:

Warning: Undefined variable $print in /index.php on line 9

In the following section, you will understand what the global keyword is and how to use a variable in the global scope.

Global Scope

The “global” keyword in PHP allows you to use variables that are defined outside the block (outside the local scope), which are written in the general PHP script. However, be careful, as using too many global variables can make your code messy.

For example.

$print = "CodedTag Tutorials.";
function func() {
   global $print; 
   echo $print; 
}
func();

Also, you can use this keyword alongside many global scope variables like this: global $x, $y, $z. For example:

$username = "Montasser";
$email = "contact@codedtag.com";

function contact() {
  global $username, $email;
  echo "Hello {$username}, if you have any question contact us at this email : {$email}";
}

contact();

You can also use another method, “$GLOBALS[…]”, to invoke the variable globally. I will use the same example as before.

$username = "Montasser";
$email = "contact@codedtag.com";

function contact() {
   
  echo "Hello {$GLOBALS['username']}, if you have any question contact us at this email : {$GLOBALS['email']}";
}

contact();

Anyway, let’s take a look at the last one, which is the static variable.

Static Variables

These are special because they retain their value between function calls. So, if you have a function that counts something, a static variable helps remember the count each time you use the function.

The following example demonstrates a function that performs an action to increase the $x variable. Let’s see how it works.

function increment() {
    $x = 0;
    echo $x;
    $x++;
}

increment();
increment();
increment();

The output: 0 0 0 

There is no change in the variable, but PHP has a keyword that allows the scope to retain the last variable value in the local scope, which is the “static” keyword.

I will use the same example as before.

function increment() {
  static $x = 0;
  echo $x;
  $x++;
}

increment();
increment();
increment();

The output will be as follows:

0 1 2

You can also use the static keyword with recursive functions.

function counter() {
     static $y = 0;
     echo $y;
     $y++;

     if( $y <= 20 ) {
       counter();
     } 
}
   
counter(); // 01234567891011121314151617181920

Anyway, let’s summarize it.

Wrapping Up

PHP variable scope is crucial, dictating where variables, functions, and classes are accessible within a program. Essentially, scope acts as a set of rules for the visibility and accessibility of code segments. PHP primarily recognizes three scopes: global, local, and static, which are as follows:

  • Global scope means any variables you create outside of functions or classes can be used all over your program.
  • Local scope refers to variables inside a function or class; you can only use them there. You can’t use them outside of where you made them.
  • Static scope is for variables that act like they’re in local scope, but they can remember their value each time you use the function. It’s like they have a good memory.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is variable scope in PHP?

    Variable scope in PHP refers to where a variable can be accessed or used within a program. In PHP, there are three main types of scope: - Local Scope: Variables declared inside a function, accessible only within that function. - Global Scope: Variables declared outside any function, accessible throughout the entire program when explicitly referenced. - Static Scope: Local variables that “remember” their value across function calls, thanks to the static keyword. Scope rules help prevent errors by controlling where variables are valid, keeping your code organized and efficient.
  • What is the difference between global and local scope in PHP?

    In PHP, global scope refers to variables declared outside any function or class. These variables are accessible anywhere in the program, but you need to use the global keyword or the $GLOBALS array to access them inside functions. On the other hand, local scope variables are defined within a function. They’re only accessible within that function, meaning they can't be used outside of it. This keeps local variables private to their function, which helps avoid accidental interference with other parts of the program.
  • How do you make a variable global in PHP?

    To make a variable global in PHP, declare it outside of any function or class, like this:
    $globalVar = "I'm accessible globally!";
    Inside a function, you can access this global variable in two ways: Use the global keyword:
    function showVar() {
        global $globalVar;
        echo $globalVar;
    }
    Use the $GLOBALS array:
    function showVar() {
        echo $GLOBALS['globalVar'];
    }
    Both methods allow you to use a globally declared variable inside functions.
  • What is the purpose of the static keyword in PHP?

    The static keyword in PHP is used to declare a variable that retains its value across multiple function calls. Normally, local variables reset each time a function runs. However, a static variable “remembers” its last value, which is helpful when you need a persistent counter or want to track the state between calls.
    function counter() {
        static $count = 0;
        echo $count;
        $count++;
    }
    
    counter(); // Outputs: 0
    counter(); // Outputs: 1
    counter(); // Outputs: 2
    
    The static variable $count retains its value across each call to counter().
  • How can you access a global variable inside a function in PHP?

    You can access a global variable inside a function in PHP using either the global keyword or the $GLOBALS array. Using the global keyword:
    $name = "CodedTag";
    function greet() {
        global $name;
        echo "Hello, $name!";
    }
    greet(); // Outputs: Hello, CodedTag!
    Using the $GLOBALS array:
    $name = "CodedTag";
    function greet() {
        echo "Hello, " . $GLOBALS['name'] . "!";
    }
    greet(); // Outputs: Hello, CodedTag!
    Both methods give you access to global variables within functions.
  • Why do we use static variables in PHP?

    Static variables are used in PHP when you want a local variable to retain its value across function calls. They’re particularly useful for keeping a count or storing data between recursive calls without relying on global variables. For example, a static variable can help count the number of times a function has been called:
    function callTracker() {
        static $callCount = 0;
        $callCount++;
        echo "Function has been called $callCount times.";
    }
    
    callTracker(); // Outputs: Function has been called 1 times.
    callTracker(); // Outputs: Function has been called 2 times.
    
    Static variables allow data to persist within the function without impacting the global scope.
  • Can a PHP function access a variable outside its scope?

    A PHP function cannot directly access a variable outside its local scope without some additional setup. If you want a function to access an external (global) variable, you need to either: Use the global keyword within the function to bring that variable into scope, or Access it via the $GLOBALS array. Trying to access a non-global variable outside a function will result in an “undefined variable” error, as PHP strictly enforces variable scope.
  • What is $GLOBALS in PHP?

    $GLOBALS is a superglobal array in PHP that holds all global variables. It’s an associative array where each key is a variable name, and each value is the variable’s data. You can use $GLOBALS to access global variables from anywhere in your code, including inside functions, without explicitly declaring them as global. Here is an example:
    $greeting = "Hello, World!";
    function displayGreeting() {
        echo $GLOBALS['greeting'];
    }
    
    displayGreeting(); // Outputs: Hello, World!
    $GLOBALS is helpful when you need quick access to global variables without changing their scope.
  • How do I fix an “undefined variable” error in PHP?

    An “undefined variable” error occurs when you try to use a variable that hasn’t been defined in the current scope. To fix it: - Check if the variable was created in a different scope (e.g., inside a function) and isn’t accessible in the current scope. - Make sure spelling and capitalization are correct, as PHP variable names are case-sensitive. - If the variable should be global, ensure it’s declared outside the function and use the global keyword or $GLOBALS array to access it.
  • What are the types of variable scope in PHP?

    PHP has three main types of variable scope: - Local Scope: Variables declared inside a function and accessible only within that function. - Global Scope: Variables declared outside any function, accessible throughout the program using the global keyword or $GLOBALS array. - Static Scope: Variables declared with the static keyword, allowing them to retain their value across multiple function calls. Each type of scope serves a different purpose in organizing how variables are accessed and maintained in your PHP code.
Share on: