What is static keyword in function PHP: Explanation and Example
static keyword inside a function keeps a variable's value between multiple calls without resetting it. Unlike regular variables, a static variable preserves its state, acting like a memory inside the function.How It Works
Imagine you have a notebook where you write down a number each time you visit a place. Normally, if you start fresh every time, you forget the previous number. But if you keep the notebook, you remember the last number you wrote. In PHP, a static variable inside a function works like that notebook. It remembers its value between calls.
When you declare a variable as static inside a function, PHP does not reset it to its initial value every time the function runs. Instead, it keeps the value from the last time the function was called. This is different from normal local variables, which start fresh each time.
This helps when you want to count how many times a function runs or keep track of information without using global variables or external storage.
Example
This example shows a function that counts how many times it has been called using a static variable.
<?php function counter() { static $count = 0; $count++; echo "This function has been called $count times.\n"; } counter(); counter(); counter();
When to Use
Use static variables inside functions when you need to remember information between calls but want to keep the variable private to the function. This avoids using global variables, which can make code harder to manage.
Common use cases include:
- Counting how many times a function runs.
- Storing a cached value to avoid repeating expensive calculations.
- Maintaining state in recursive functions.
It is a simple way to keep track of data without affecting other parts of your program.
Key Points
- Static variables keep their value between function calls.
- They are local to the function and not accessible outside.
- Useful for counting, caching, or state tracking inside functions.
- Different from global variables which are accessible everywhere.