➤ The scope of a variable is the part of the script in which
the variable can be referenced or used.
• A variable declared outside a function has a
global scope
.
• A variable declared within a function has a
local scope
, and can only be accessed within that function.
For instance:
// global scope
$number = 10;
function print_num() {
echo "the number is: $number ";
}
print_num(); // outputs: Undefined variable $number
// the $number variable has a global scope, and is not accessible within the print_num() function
function task() {
$name = "Mads"; // local scope
echo "Variable name inside function is: $name";
// outputs: Variable name inside function is: Mads
}
task();
// using $name outside the function will generate an error
echo "Variable name outside function is: $name";
// Undefined variable $name