Static function-local variables retain state between successive invocations of the same function.
What It Does
Static function-local variables retain state between successive invocations of the same function. 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
Static local arrays can maintain independent counters within one execution.
<?php
function nextId(string $namespace): int { static $perNamespace = []; return $perNamespace[$namespace] = ($perNamespace[$namespace] ?? 0) + 1; }
echo nextId('a') . ':' . nextId('b') . ':' . nextId('a');
Important Behavior and Edge Cases
They are function scoped, not a reliable shared persistent cache across requests.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Static Local Variables | Static function-local variables retain state between successive invocations of the same function. |
| Related approach | Use a database or cache for cross-request counters. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Static Local Variables | They are function scoped, not a reliable shared persistent cache across requests. |
| Assuming a related mechanism has the same behavior | Use a database or cache for cross-request counters. |
Key Takeaways
- Static function-local variables retain state between successive invocations of the same function.
- They are function scoped, not a reliable shared persistent cache across requests.
- Use a database or cache for cross-request counters.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.