Scope defines the visibility and lifetime of a variable within your script. In PHP, variables have different access rules depending on where they are declared. Understanding these rules is vital for preventing data conflicts and "undefined variable" errors.
Variables declared inside a function are local to that function. They are created when the function starts and destroyed as soon as the function ends.
<?php
function myTest() {
$x = 5; // Local scope
echo "Variable x inside function is: $x";
}
myTest();
// echo $x; // This would result in an error!
?>
A variable declared outside a function has a global scope and can only be accessed outside a function.
To access a global variable from within a function, you must use the global keyword.
<?php
$x = 10;
$y = 20;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // Outputs: 30
?>
PHP also stores all global variables in an associative array called $GLOBALS[index]. The index is the name of the variable.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // Outputs: 15
?>
Normally, when a function is completed, all of its local variables are deleted. However, sometimes we want a local variable NOT to be deleted. To do this, use the static keyword.
<?php
function myCounter() {
static $count = 0;
echo $count . " ";
$count++;
}
myCounter(); // 0
myCounter(); // 1
myCounter(); // 2
?>
include or require.
global keyword to be used inside.