PHP Syntax Variables Scope Global

 

- Info:

- Global variable can be accessed in any part of the program.

- Variable is global if it is declared outside any function.

 

- GLOBAL:

- To modify a global variable, it must be explicitly declared to be global in the function in which it is to be modified.

- This is done by using keyword GLOBAL before it.

- If you ommit GLOBAL the variable $somevar be considered local, implicitly set to 0 and then incremented by 1.

- Create PHP Console Application Test.php.

 

Test.php

<?php

$somevar = 15;

 

function addit() {

GLOBAL $somevar;

$somevar++;

echo "Somevar is $somevar";

}

 

addit();

?>

 

- $GLOBALS[]:

- Instead of using keyword GLOBAL you can access global variable directly through $GLOBALS array.

- This array contains all global variables which can be accessed using their name as associative index.

- Create PHP Console Application Test.php.

 

Test.php

<?php

$somevar = 15;

 

function addit() {

$GLOBALS["somevar"]++;

}

 

addit();

 

echo "Somevar is ".$GLOBALS["somevar"];

?>