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
globalor$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:
$messageis 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:
$siteNameis a global variable declared outside the function.- To access it inside
showSiteName(), we use theglobalkeyword.
📝 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
globalkeyword.
📝 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:
$countis a static variable, so it keeps its value across function calls.- Each time the function runs,
$countincrements instead of resetting.
🎯 Key Takeaways
- Local Variables: exist inside functions only.
- Global Variables: exist outside functions but need
globalor$GLOBALSto 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!