In PHP, the scope of a variable determines where it can be accessed. Variables in PHP can be categorized as:
- ๐น Local Variables โ Declared inside a function, accessible only within that function.
- ๐น Global Variables โ Declared outside functions, accessible anywhere using
global
or$GLOBALS
. - ๐น Static Variables โ Retains its value across multiple function calls.
๐ Example 1: Local Variables
Local variables are defined inside a function and cannot be accessed outside of it.
<?php function localExample() { $message = "Hello from inside the function!"; echo $message; } localExample(); // This will cause an error because $message is not available outside the function // echo $message; ?>
Explanation:
$message
is declared insidelocalExample()
.- It is only accessible within the function and will cause an error if accessed outside.
๐ Example 2: Global Variables
Global variables are defined outside functions but can be accessed inside functions using the global
keyword or $GLOBALS
array.
<?php $siteName = "PHP Learning Hub"; function showSiteName() { global $siteName; // Using global keyword echo "Welcome to $siteName!"; } showSiteName(); ?>
Explanation:
$siteName
is a global variable declared outside the function.- To access it inside
showSiteName()
, we use theglobal
keyword.
๐ Example 3: Using $GLOBALS Array
Another way to access global variables inside functions is by using $GLOBALS
.
<?php $x = 10; $y = 20; function sumNumbers() { echo "Sum: " . ($GLOBALS['x'] + $GLOBALS['y']); } sumNumbers(); ?>
Explanation:
$GLOBALS['x']
and$GLOBALS['y']
access the global variables.- This allows us to use them inside the function without the
global
keyword.
๐ Example 4: Static Variables
Static variables retain their value between function calls.
<?php function countCalls() { static $count = 0; // Static variable $count++; echo "Function called $count times.<br>"; } countCalls(); countCalls(); countCalls(); ?>
Explanation:
$count
is a static variable, so it keeps its value across function calls.- Each time the function runs,
$count
increments instead of resetting.
๐ฏ Key Takeaways
- Local Variables: exist inside functions only.
- Global Variables: exist outside functions but need
global
or$GLOBALS
to be accessed inside. - Static Variables: retain their values between function calls.
๐ Practice Time!
Modify these examples and experiment with different values to understand how variable scope works in PHP!