Global vs. local variables in PHP functions

Опубликовано: 04 Май 2026
на канале: PHP Explained
688
11

Variables declare inside the function are called local variables.
Local variables can be accessed into inside of the function.

Check the example. Variables, x, y, and z are confined within the function sum(). These variables cannot be accessed from outside the function.
function sum()
{
$x = 5;
$y = 10;
$z = $x + $y;
return $z;
}
echo sum();

Variables declare outside the function are called global variables.
Global variables can be accessed from anywhere of the code outside of the functions.
Global variables can be accessed from a function using the global keyword.

See the example. Variables x and y are declared outside the function and hence it has global scope and can be accessed from anywhere including functions. We have used keyword global with variable names to access and start using them.
$x = 5;
$y = 10;
function sum()
{
global $x, $y;
$z = $x + $y;
return $z;
}
echo sum();

Conclusion is global variables have wider scope to use rather than the local variables.