PHP Variables

Variables are used to store information which can be referenced and manipulated within a computer program. These variables also play a vital role in labeling data with a descriptive name, which makes it easier for the users to understand the program clearly and impressively. Some programmers also consider the variables as containers which can hold information.

Scope of a variable

The scope of a variable can be defined as its extent in program. It can be accessed in the program. Easily explained, it is the portion of a program within which it is clearly visible and accessible.

PHP has three variable scopes

  • Local variable
  • Global variable
  • Static variable

Local variable

These are the variables which are declared within a function. It is so named as it has scope only within that particular function. It is not able to access outside the particular function. Any declaration of a variable that you use outside the function with the similar name, as the one used within the function, becomes a completely different one.

Code

 <?php

$num = 60;

Function local_var()

{

//This $num is local to this function

//the variable $num outside this function

//is a completely different variable

$num = 50;

echo “local num = $num \n”;

}

local_var();

//$num outside function local_var() is a

// completely different variable than that of

// inside local_var()

echo “Variable num outside local_var() is $num \n”;

?>

output

Local num = 50

Variable num outside local_var() is 60

Global variable

The variables that are declared outside a particular function are known as global variables. One can access directly outside that particular function. In order to access the variable within a function, one need to use the word “global”, in front of the variable to refer to the particular global variable.

Example

<?php

$num = 20;

// functionto demonstrate use of global variable

Function global_var()

{

//we have to use global keyword before

// the variable $num to access within

// the function

global $num;

echo “variable num inside function : $num \n”;

}

global_var();

echo “Variable num outside function : $num \n”;

?>

Output

Variable num inside function : 20

Variable num outside function : 20

Static variable

It is the characteristic of PHP to delete a variable. Once the variable completes its execution and the entire memory is freed, it is to be deleted. But sometimes, the variables need to be stored even after the function is executed. To conduct this, PHP developers use static keyword and the variables then are known as the static variables.

Example

<?php

// function to demonstrate static variables

functionstatic_var()

{

// static variable

static $num = 5;

$sum = 2;

$sum++;

$num++;

echo $num, “\n”;

echo $sum, “\n”;

}

// first function call

static_var();

// second function call

static_var();

?>

Output 

6

3

7

3

Leave a Comment