Why does your variable suddenly disappear inside a function? Discover the secret of variable scope!
Why Variable scope in functions in PHP? - Purpose & Use Cases
Imagine you write a PHP script where you set a variable outside a function, then try to use it inside that function. You expect it to work, but it doesn't. You have to copy or rewrite the variable inside every function that needs it.
This manual way is slow and confusing. You might forget to update the variable in all places, causing bugs. It's like having to carry a note everywhere you go instead of just having it where you need it.
Understanding variable scope in functions helps you know exactly where variables live and when you can use them. PHP lets you control this so your code is cleaner and less error-prone.
$x = 5;
function show() {
echo $x; // Error: undefined variable
}$x = 5;
function show() {
global $x;
echo $x; // Works fine
}Knowing variable scope lets you write functions that use or protect data correctly, making your programs reliable and easier to fix.
Think of a recipe book (your program). Ingredients (variables) are stored in the kitchen (global scope). But when cooking a dish (function), you need to know which ingredients you can use directly or must bring in explicitly.
Variables exist in different places called scopes.
Functions have their own scope separate from the main code.
Using scope rules avoids bugs and keeps code organized.