Home Tutorial Php Phpbasics Tutorial PHP Variable Scope

 
 

PHP Variable Scope
Posted on: March 17, 2010 at 12:00 AM
This PHP tutorial is all about the scope of a variable in PHP. The Variable in PHP has a life in the program and in programming language we call it as the scope means the area in which the value of the variable is applicable.

PHP Variable Scope:

In every language every variable has a scope, may be within a block or within the whole program etc.  Generally the scope of a variable in PHP is inside a function or inside a block. To make the variable global either use global keyword or $GLOBALS array keyword.

Another way of scoping  is static variable,  the scope of a static variable exists only in a local function scope, but the value persists even after the execution of the program.

Scope of Variables in PHP with Example:

<?php

$a=34;

{

echo "Value of \$a inside the block is= ".$a;

$a=45;

echo "Value of \$a inside the block is= ".$a;

}

echo "Value of \$a outside the block is= ".$a;

?>

 

Output:

Value of $a inside the block is= 34
Value of $a inside the block is= 45
Value of $a outside the block is= 45

 

Example:

<?php

$a=4;

add();

function add()

{

$a=34;

global $a;

echo $a + $a;

}

?>

Output:

8

Example:

<?php

function display()

{

$a=23;

echo $a."<br/>";

}

$a="string";

display();

echo $a;

?>

Output:

23
string

Example:

<?php

function display()

{

static $a=-1;

echo $a++."<br/>";

}

display();

display();

?>

Output:

-1
0

Example:

<?php

$a=43;

$b="Hello";

function Disp()

{

echo $GLOBALS['a'];

echo "<br/>".$GLOBALS['b'];

}

Disp();

?>

Output:

43
Hello

 

 

 

Related Tags for PHP Variable Scope:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.