Skip to content

PHP Tutorial Variables and Constants

Static Variables

Lesson 30 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
function countCalls(): int
{
    static $count = 0;
    $count++;
    return $count;
}

echo countCalls() . "\n";
echo countCalls() . "\n";
echo countCalls();
Output
OUTPUT
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.

index.php
PHP
<?php
function countCalls(): int
{
    $count = 0;
    $count++;
    return $count;
}

echo countCalls() . countCalls() . countCalls();
Output
OUTPUT
111

A practical use: simple caching

Static variables are handy when something is expensive to build and you want to build it only once.

index.php
PHP
<?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"];
Output
OUTPUT
(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 static is also used for static class properties and methods. That is a different feature with the same keyword.
lightbulb
Use this sparingly
A static variable is a kind of hidden state. It is fine for counters and small caches, but if you need to share state widely, use a class.