Understand variable scope in PHP, including local and global variables. Learn how to use the global keyword and access global variables inside functions with clear code examples.
<?php
function testFunction() {
$x = 10; // Local variable
echo $x; // Output: 10
}
testFunction();
echo $x; // Error: Undefined variable
?>
<?php
$x = 10; // Global variable
function testFunction() {
echo $GLOBALS['x']; // Accessing global variable
}
testFunction(); // Output: 10
?>
$GLOBALS - The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
global
keyword.<?php
$x = 10; // Global variable
function testFunction() {
global $x;
echo $x; // Output: 10
}
testFunction();
?>
printLocalVar()
that defines a local variable $message
with the value "Hello, PHP!"
.$message
inside the function.$message
outside the function. What happens? Explain why.<?php
function printLocalVar() {
// Your code here
}
// Call function and test
?>
$counter = 0;
outside any function.incrementCounter()
that accesses $counter
using the $GLOBALS
array and increments it by 1
.$counter
outside the function. What is the output?2
$total = 50;
.applyDiscount()
that:
global
keyword to access $total
.$total
by 10%).$total
outside the function.45
[1] “Variable Scope,” PHP Manual. [Online]. Available: https://www.php.net/manual/en/language.variables.scope.php. [Accessed: Apr. 29, 2025].