Scope of variables in php

In programming world a “variable” refers to a space in memory where we store values of any types. We use variable to store data value and pass that value to a functions/method in a program. This article explains the scope of the variables in PHP.

Note: A Function or Method in any program is a named block that performs a specific task. We use the term ‘Function’/’Method’ interchangeably in programming languages. So please don’t confuse with these two terms.

We use variables with functions to act properly in any program. Without function we can use variable anywhere in a program, for example:

$x = 5;  // declaring and initializing variable

function test() {
$x += 3;
echo $x;

Here the variable $x inside the function test() is a different variable than the variable $x outside the function. The value of the outer $x remains 5 throughout the life of the page.

The extent to which a variable can be seen in a program is called the scope of the variable.  Variables created within a function are inside the scope of the function (also called as function level scope).  Variables created outside of functions and objects have global scope and exist anywhere outside of those functions and objects.  PHP also provides both function level and global scope variables often referred to as super-global variables, for example ($_POST[]).

scope of variable php

Types of Variables in PHP

Global variables:

When we want a variable in the global scope to be accessed from within a function, we use the ‘global’ keyword in that function, for example:

$x = 10;
function check() {
global $x;     // we use global keyword here
$x += 5;
echo $x;

Note:  We must include global keyword in a function before any use of global variables or variables we want to access, because they are declared before the body of the function. Function parameters can never be global variables.

Static Variables:

In PHP we declare function variables ‘static’ just like C language.  A static variable retains its value between all call to the function and is initialized during a script execution only the first time the function is called.

Note: To declare a variable static, always use ‘static’ keyword before variable.

For example:

function teach() {
static $cut = 0;     // using static keyword to declare static variable
return $cut++;
for($x=1; $x<=5; $x++){
print teach();

Output: 01234

Here in above example when the function teach() is called for the first time, the static variable $cut is assigned a value of 0.  The value is returned and $cut is incremented.  When the function ends $cut is not destroyed like other non-static variable, and its value remains the same until the time teach() called.

Uploaded by:  Author