PHP Variable Scope


 

PHP Variable Scope

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.

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:

0

8

Example:

<?php

1

function display()

{

$a=23;

2

echo $a."<br/>";

}

$a="string";

3

display();

echo $a;

?>

4

Output:

23
string

5

Example:

<?php

function display()

6

{

static $a=-1;

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

7

}

display();

display();

8

?>

Output:

9

-1
0

Example:

<?php

0

$a=43;

$b="Hello";

1

function Disp()

{

echo $GLOBALS['a'];

2

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

}

Disp();

3

?>

Output:

43
Hello

4

 

 

 

5

Ads