You are currently viewing What are Scope of Variable in PHP | Explained
  • Post category:PHP

What are Scope of Variable in PHP | Explained

Scope of Variable in PHP

In this article, we will see about the scope of variable in PHP.

What is PHP Scope

  • Scope indicates the accessibility and visibility of variables.
  • PHP variables will be either in the local scope or global scope.
  • It is divided into two types, local scope, and global scope.

Local scope

Any variable declared inside a function is considered as in local scope or function scope.
It can be accessed only inside that function where it is declared.

Note: Local scope variables will be available only in the function execution (i.e are created as soon as the control enters the function body and deleted as soon as the control exits the function body).

Ex:

function display()
{
$b=20;
echo"b = "; //20
}
display();
echo "b=", $b; // error:b is not defined.
  1. In the above code, we created a function “display()”.
  2. We assigned 20 to variable ‘b’ inside the function and printed the ‘b’. Then call the display() function.
  3. And finally, we print ‘b’, it says error because “b variable” is inside the function.

Global scope

Any variable declared outside a function is considered as in global scope.
It can be accessed anywhere in the script.

Note: Global scope variable will be available throughout the script execution. If you want to access a global scope variable inside a local scope you must use the global keyword.

Ex:

$a=10; //global scope
echo "a= ", $a; //10
function display()
{
echo "a=", $a; //undefined error
global $a;
echo "a= ",$a; //10
}
display();
  1. In the above code, we created the global variable “a” with an assigned value of 10. Then, we print the variable ‘a using an echo statement.
  2. Then we create a display() function within that we have a print variable ‘a’. It returns an undefined error.
  3. To display the value of variable ‘a”, we say “global $a”.
  4. Then we print variable ‘a’ and it returns “10” successfully.

Leave a Reply