Variable scope in PHP (local and global variables)

This tutorial explains variable scope in PHP. The scope of a variable refers to where a variable can be used in a program. A variable’s scope can either be global or local

Global variables are variables that have been declared outside of a function and can be accessed anywhere in the program including inside functions. Local variables are made inside a function and can only be access inside that function they were created in. In other words, the local variable from one function cannot be used in another function or outside the function in the main part of the program. However, local variables can be made global if the programmer needs to use the variable outside the function it was created in.

Watch the video below and then scroll down to see the sample code.

Sample PHP code:

  $globalVariable = 10;

  function scopeCheck(){
    global $globalVariable;
    // $globalVariable can be accessed by this function because it is now global
    $globalVariable = 20;
    echo $globalVariable;

    // $localVariable can only be accessed inside this function because it is local
    // Writing global $localVariable; will make the variable global.
    $localVariable = 50;

  echo $globalVariable; // this will work because variable is global
  echo $localVariable; // this will not work because variable is local