PHP 8 Intermediate Basics · 1 min read

Static variable in a function

Start the PHP 8 learning path »

❮ PHP 8 Home All Tutorials ❯

How do I keep a value between function calls?

static $count.

Example

PHP 8 Example
<?php
function hits() {
  static $count = 0;
  $count++;
  return $count;
}
echo hits(); // 1
echo hits(); // 2

Line-by-Line Walkthrough

Static preserves value across calls in the same request.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…