Web Analytics

PHP Function Scope & Static Variables

Beginner~20 min read

Understanding variable scope is crucial for writing bug-free code. Learn about global, local, and static variables, and how they behave in different contexts!

Output
Click Run to execute your code

Global Scope

<?php
$globalVar = "I'm global";

function test() {
    global $globalVar;
    echo $globalVar;
}

test();  // "I'm global"
?>

Local Scope

<?php
function example() {
    $local = "I'm local";
    return $local;
}

echo example();
// echo $local;  // Error! Not accessible
?>

Static Variables

<?php
function counter() {
    static $count = 0;
    $count++;
    return $count;
}

echo counter();  // 1
echo counter();  // 2
echo counter();  // 3
?>

Summary

  • Global: Accessible everywhere with global
  • Local: Only inside function
  • Static: Retains value between calls
  • Lifetime: Static persists, local doesn't

What's Next?

Congratulations! You've completed Module 5. Next, dive into Arrays - PHP's most powerful data structure!