Share on Google+Share on Google+

PHP Variable Scope

Advertisement
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

 

 

 

Advertisements

Advertisement

Posted on: March 17, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.