Using Static Variables in PHP: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-18 09:18:03   5749  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.

You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.

Syntax:



<?php
   function trackerFunction() {
      STATIC $count = 10;
      $count++;
      print $count;
      print "<br />";
   }
   
   trackerFunction();
   trackerFunction();
   trackerFunction();
?>


Output:

This will produce the following result



11
12
13


we will discuss more about static keyword later



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.