A normal local variable is created fresh every time a function runs and is destroyed when it ends. A static variable is different. It remembers its value between calls.
<?php
function countCalls(): int
{
static $count = 0;
$count++;
return $count;
}
echo countCalls() . "\n";
echo countCalls() . "\n";
echo countCalls();
1
2
3
The line static $count = 0; runs only the first time. After that, PHP keeps $count alive for the function.
Without static, the function would print 1 three times.
<?php
function countCalls(): int
{
$count = 0;
$count++;
return $count;
}
echo countCalls() . countCalls() . countCalls();
111
A practical use: simple caching
Static variables are handy when something is expensive to build and you want to build it only once.
<?php
function getSettings(): array
{
static $settings = null;
if ($settings === null) {
echo "(loading settings)\n";
$settings = ["theme" => "dark", "lang" => "en"];
}
return $settings;
}
echo getSettings()["theme"] . "\n";
echo getSettings()["lang"];
(loading settings)
dark
en
The loading message appears once. The second call reuses the stored array.
Things to know
- The variable is private to the function. Code outside cannot read it.
- The starting value must be a plain value, not the result of a function call (before PHP 8.3).
- The word
staticis also used for static class properties and methods. That is a different feature with the same keyword.