PHP/Variables: Difference between revisions
wikademia>Kev →Variable types: Added boolean info |
wikademia>Kev Added some stuff about variable scope |
||
| Line 58: | Line 58: | ||
var $a; | var $a; | ||
?> | ?> | ||
==Scope== | |||
Scope refers to what can actualy modify a variable, e.g: | |||
<?php | |||
$var = 1; | |||
require 'another_page.php'; | |||
?> | |||
The page 'another_page.php' has full acess to the variable 'var'. | |||
<?php | |||
$var = 'Test'; | |||
function test() | |||
{ | |||
echo $var; | |||
} | |||
test(); | |||
?> | |||
The above would output nothing, since functions have there own scope, variables outside that scope would not be available. | |||
===Globals=== | |||
You can force functions to acess other variables by using the global keyword, e.g: | |||
<?php | |||
$var = 'Test'; | |||
function test() | |||
{ | |||
global $var; | |||
echo $var; | |||
} | |||
test(); | |||
?> | |||
Would output: Test | |||
Or you can use the $GLOBALS array, like this: | |||
<?php | |||
$GLOBALS['var'] = 'Test'; | |||
function test() | |||
{ | |||
echo $GLOBALS['var']; | |||
} | |||
test(); | |||
?> | |||
===Static Variables=== | |||
Static variables exist within a function and are saved after the function executes, e.g: | |||
<?php | |||
function increment() | |||
{ | |||
static $a = 0; | |||
echo $a; | |||
$a++; | |||
} | |||
increment(); // 0 | |||
increment(); // 1 | |||
increment(); // 2 | |||
increment(); // 3 | |||
?> | |||
If the variable 'a' was not static, it would echo 0 each time. | |||
== Referencing == | == Referencing == | ||