Static local variables preserve a function-local value between calls during the same PHP execution.
What It Does
Static local variables preserve a function-local value between calls during the same PHP execution. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
function nextSerial(): int { static $serial = 0; return ++$serial; }
echo nextSerial() . ', ' . nextSerial();
Example 2: Another Case
Examine the edge case and the observable result.
<?php
function cachedLabel(int $id): string { static $cache = []; return $cache[$id] ??= 'Item-' . $id; }
echo cachedLabel(7);
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
function counter(): int { static $hits = 0; return ++$hits; }
foreach (range(1, 3) as $_) echo counter() . ' ';
Important Behavior and Edge Cases
They are not a cross-request cache under ordinary PHP-FPM and can retain state in persistent workers.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Static Local Variables Explained | Static local variables preserve a function-local value between calls during the same PHP execution. |
| Related approach | Use external storage for request-independent shared counters. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Static Local Variables Explained | They are not a cross-request cache under ordinary PHP-FPM and can retain state in persistent workers. |
| Assuming a related mechanism has the same behavior | Use external storage for request-independent shared counters. |
Key Takeaways
- Static local variables preserve a function-local value between calls during the same PHP execution.
- They are not a cross-request cache under ordinary PHP-FPM and can retain state in persistent workers.
- Use external storage for request-independent shared counters.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.