phpPHP
Module 12: Scope and ReferencesBeginner40 min read

Variable Scope, Static Variables, References (&) & Avoiding Global State

Understand PHP function scope, static local variables, superglobal visibility, symbol-table aliases (&), and why global state harms testability.

Key Takeaways & Core Concepts
  • `static` local variables: Retain their value across calls to the same function.
  • Why avoid `global`: Hidden dependencies make unit testing, concurrency, and refactoring brittle—use dependency injection instead!

Variable Scope, Static Variables, References (&) & Avoiding Global State

### 1. Scope Rules in PHP Variables inside a function are local and isolated (unlike JS/Python, outer globals are not implicitly visible inside functions unless imported via global $x; or $GLOBALS).

  • `static` local variables: Retain their value across calls to the same function.
  • Why avoid `global`: Hidden dependencies make unit testing, concurrency, and refactoring brittle—use dependency injection instead!
1. Static Counter & Pass-by-Reference
1<?php
2function nextId(): int {
3 static $id = 0;
4 return ++$id;
5}
6function doubleVal(int &$n): void { $n *= 2; }
7
8$x = 5;
9doubleVal($x);
10echo "IDs: " . nextId() . ", " . nextId() . " | x = $x\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Note: `static $id` persists across `nextId()` calls; `&$n` mutates `$x` in place.
Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)