PHP Variable Scope
Variable Scope determines where a variable can be accessed in a program.
Understanding scope is extremely important because many bugs happen due to incorrect variable access.
Why Scope Matters
Scope helps:
✅ Prevent accidental variable modification
✅ Improve security
✅ Organize code properly
✅ Reduce bugs
✅ Build scalable applications
Example
$name = "Aayan";
Can we use $name everywhere?
Not necessarily.
Its accessibility depends on its scope.
Types of Scope
PHP has:
- Global Scope
- Local Scope
- Static Scope
- Parameter Scope
- Class Property Scope
Global Scope
Variables declared outside functions belong to global scope.
Example:
$name = "Aayan";
This variable exists globally.
Problem
$name = "Aayan";
function test() {
echo $name;
}
Output:
Undefined variable
Because functions create their own local scope.
Accessing Global Variables
Use:
global
Example:
$name = "Aayan";
function test() {
global $name;
echo $name;
}
test();
Output:
Aayan
Multiple Globals
$a = 5;
$b = 10;
function add() {
global $a, $b;
echo $a + $b;
}
$GLOBALS Array
PHP automatically stores global variables.
Example:
$name = "Aayan";
function test() {
echo $GLOBALS["name"];
}
Output:
Aayan
Structure
$GLOBALS
│
├── _GET
├── _POST
├── _SERVER
├── name
└── age
Local Scope
Variables created inside functions belong to local scope.
Example:
function test() {
$name = "Aayan";
echo $name;
}
Works only inside that function.
Invalid Access
function test() {
$name = "Aayan";
}
echo $name;
Output:
Undefined variable
Memory Representation
Function Start
↓
Create Local Variables
↓
Execute Function
↓
Destroy Variables
Function Parameters
Parameters are local variables.
Example:
function greet(
string $name
) {
echo $name;
}
$name only exists inside this function.
Scope Isolation
$name = "Global";
function test() {
$name = "Local";
echo $name;
}
test();
echo $name;
Output:
LocalGlobal
Because they are different variables.
Static Scope
Normally:
function counter() {
$count = 0;
$count++;
echo $count;
}
Calling:
counter();
counter();
counter();
Output:
111
Variable resets every time.
Static Variables
function counter() {
static $count = 0;
$count++;
echo $count;
}
Output:
123
The variable remains in memory.
How Static Works
First Call:
count = 0
Second Call:
count = 1
Third Call:
count = 2
Real Example
function generateId() {
static $id = 0;
return ++$id;
}
Anonymous Function Scope
Closures cannot access outside variables automatically.
Invalid
$name = "Aayan";
$fn = function() {
echo $name;
};
Produces:
Undefined variable
Using use()
$name = "Aayan";
$fn = function() use (
$name
) {
echo $name;
};
$fn();
Output:
Aayan
Passing by Reference
$count = 0;
$fn = function() use (
&$count
) {
$count++;
};
$fn();
echo $count;
Output:
1
Arrow Function Scope
Arrow functions automatically inherit variables.
Example:
$name = "Aayan";
$fn =
fn() => $name;
echo $fn();
Output:
Aayan
Class Scope
Classes introduce another type of scope.
Local Variable
class User {
public function test() {
$name = "Aayan";
}
}
Property Scope
class User {
public string $name;
}
Access:
$user->name
Accessing Class Variables
Use:
$this
Example:
class User {
private string $name =
"Aayan";
public function test() {
echo $this->name;
}
}
Static Property Scope
class Config {
public static string
$version = "1.0";
}
Access:
Config::$version;
Constants Scope
class Main {
public const VERSION =
"1.0";
}
Access:
Main::VERSION;
Scope Resolution Operator
PHP uses:
::
This operator is called:
Scope Resolution Operator
Examples
self::
parent::
static::
ClassName::
self::
References current class.
self::VERSION
parent::
References parent class.
parent::onEnable();
Used heavily in PocketMine.
static::
Late Static Binding.
Advanced OOP feature.
PocketMine Examples
Plugin Instance
class Main
extends PluginBase {
private array $players =
[];
}
The property is available throughout the object.
Commands
public function onCommand(
CommandSender $sender,
Command $command,
string $label,
array $args
): bool {
}
All parameters are local.
Event Listener
public function onJoin(
PlayerJoinEvent $event
): void {
$player =
$event->getPlayer();
}
$player only exists inside the method.
Common Mistakes
Using Local Variables Globally
❌
function test() {
$x = 5;
}
echo $x;
Forgetting $this
❌
echo name;
✅
echo $this->name;
Excessive Globals
Avoid:
global
Too much global usage creates messy code.
Best Practices
✅ Prefer dependency injection.
✅ Use class properties instead of globals.
✅ Keep variables inside smallest scope possible.
✅ Avoid global state.
Real Project Example
class EconomyManager {
private array $money =
[];
}
Better than:
$GLOBALS["money"];
Exercises
Exercise 1
Create a global variable.
Access it using:
global
Exercise 2
Create:
static $counter
Exercise 3
Create a closure using:
use()
Exercise 4
Create a class property.
Access it using:
$this
Challenge
Create:
PlayerManager
Store:
players
money
ranks
using proper class scope.
Quiz
Which keyword accesses global variables?
Answer
global
Which variable stores all globals?
Answer
$GLOBALS
Which keyword accesses class properties?
Answer
$this
Which operator accesses static members?
Answer
::
References
PHP Scope:
https://www.php.net/manual/en/language.variables.scope.php
Anonymous Functions:
https://www.php.net/manual/en/functions.anonymous.php
Closures:
https://www.php.net/manual/en/class.closure.php
Next Chapter
➡ PHP Strings