PHP Variables Scope

Variable in PHP can be declared anywhere in the script. So the scope of the variable is defined by where it can be accessed in the script.
In other words, it is the context where a variable is defined and accessed.

PHP has three different kinds of scopes:

  • Local Scope
  • Global Scope
  • Static Scope

Local Scope

A variable declared inside a function has a local scope. This kind of variables can only be accessed within that function:

Variable with local scope:

function locScope() {
  $data = "hello"; // local scope
  echo "<p>local variable value is: $data</p>";
// Using $data outside the function throws an error.
echo "<p>Variable outside local scope: $data</p>";

Global Scope

A variable that is declared outside a function has a global scope. This kind of variables can only be accessed from outside a function:

Variable with global scope:

$data = 120.3; // global scope

function gloScope() {
  // Using $data inside this function throws an error
  echo "<p>Variable $data inside function is: $data</p>";

echo "<p>Variable $data outside function is: $data</p>";

PHP global Keyword

To access the global variable within the function the global keyword is used. Add the global keyword right before the variable:

global keyword

$num1 = 25;
$num2 = 20;

function glokey() {
  global $num1, $num2;
  $result = $num1 + $num2;

echo $result; // outputs 45

PHP static Keyword

Variables are automatically destroyed after the function execution is completed. The static keyword is used if we want to keep the local variable after the function execution.

To do this, use the static keyword in front of the variable:

function static() {
  static $num = 0;
  echo $num;

static();// output is 1
static();// output is 2
static();// output is 3

Leave a Reply

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