PHP Variable Scope: Local, Global & Static

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.

    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 = "[email protected]";
    
    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 = "[email protected]";
    
    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!

    Similar Reads

    PHP Elvis Operator: How (?:) Works with Examples

    The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional…

    PHP Associative Array: Optimal Data Organization

    The PHP associative array is a structured collection wherein data elements are organized into lists or groups. Each element is…

    PHP filter_id Function: How to Retrieve PHP Filter IDs

    Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

    PHP cURL: HTTP Requests and Responses in PHP

    In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the…

    PHP Spread Operator: Understand How (…) Syntax Works

    Before the spread operator, PHP developers had to pass array items to a function using extra steps. They often had…

    Class and Object in PHP: How They Work with a Real Example

    Classes and objects are important parts of OOP in PHP. They help you organize your code so you can update…

    PHP OOP Programming: A Complete Tutorial

    A complex web application needs proper organization and maintenance to keep your code structured. This is where PHP Object-Oriented Programming…

    PHP Array Operators: Union, Equality, Identity

    PHP arrays serve as powerful tools for storing multiple values in a single variable. To manipulate arrays efficiently, PHP provides…

    PHP Static Property: How It Works & Examples

    PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article,…

    PHP explode Function: How it Works with Examples

    When you deal with text in PHP, sometimes you need to break it into parts. This is common when users…

    Previous Article

    PHP Callable & Callback: Pass a Function to Another

    Next Article

    PHP IF Statement: A Guide to Conditional Logic

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.