SoFunction
Updated on 2025-03-10

Detailed explanation of the use of static variables and static variables in PHP

Static variables only exist within the scope of the function, that is, static variables only exist on the stack. Common variables in functions will be released after the function ends, such as local variables, but static variables will not. That is to say, the next time this function is called, the value of the variable will be retained.

Just add the keyword static before the variable, and the variable becomes a static variable.

<?php
  function test()
  {
    static $nm = ;
    $nm = $nm * ;
    print $nm."<br />";
  }
  // First execution, $nm =  test();
  // First execution, $nm =  test();
  // First execution, $nm =  test();
?>

Program running results:
1
2
2
4
3
8

After the function test() is executed, the value of the variable $nm is saved.

Static properties are often used in class, such as static members and static methods.

Program List: Static member of the class

The static variable $nm belongs to the class nowamagic, not to an instance of the class. This variable is valid for all instances.

:: is a scope-qualified operator. Here we use the self scope, not the $this scope. The $this scope only represents the current instance of the class, and self:: represents the class itself.

<?php
  class nowamagic
  {
    public static $nm = ;
    function nmMethod()
    {
      self::$nm += ;
      echo self::$nm . '<br />';
    }
  }
  $nmInstance = new nowamagic();
  $nmInstance -> nmMethod();
  $nmInstance = new nowamagic();
  $nmInstance -> nmMethod();
?>

Program running results:
1
3
2
5

Program List: Static properties

&lt;?php
  class NowaMagic
  {
    public static $nm = '';
    public function nmMethod()
    {
      return self::$nm;
    }
  }
  class Article extends NowaMagic
  {
    public function articleMethod()
    {
      return parent::$nm;
    }
  }
  // Access static variables by acting on qualifying operators  print NowaMagic::$nm . "&lt;br /&gt;";
  // Call the class method  $nowamagic = new NowaMagic();
  print $nowamagic-&gt;nmMethod() . "&lt;br /&gt;";
  print Article::$nm . "&lt;br /&gt;";
  $nmArticle = new Article();
  print $nmArticle-&gt;nmMethod() . "&lt;br /&gt;";
?&gt;

Program running results:




Program List: Simple static constructor

PHP does not have a static constructor, you may need to initialize a static class. There is a very simple method, directly call the class's Demonstration() method after the class definition.

<?php
function Demonstration()
{
  return 'This is the result of demonstration()';
}
class MyStaticClass
{
  //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
  public static $MyStaticVar = null;
  public static function MyStaticInit()
  {
    //this is the static constructor
    //because in a function, everything is allowed, including initializing using other functions
    self::$MyStaticVar = Demonstration();
  }
} MyStaticClass::MyStaticInit(); //Call the static constructor
echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>

Program running results:

This is the result of demonstration()

Below is an introduction to the use of PHP static variable static

The static keyword is very common in C# programming and is used to denote static members belonging to the type itself rather than to a specific object. The static modifier can be used for classes, fields, methods, properties, operators, events, and constructors, but cannot be used for types other than indexers, destructors, or classes. Classes, functions and variables declared as static will not reference instance methods or variables. In addition, once a static modifier is added in C#, all variables and methods inside it must be static. Static variables and methods must be referenced by class names and cannot be referenced by instance objects.

So what is the difference between static keywords in php and C#?

Declaration scope

Compared with C#, the usage scope of static variables in PHP is wider. We can not only add static modifiers before classes, methods or variables, but we can even add static keywords to variables inside functions. The variable with the static modifier added will not be lost even after the function is executed, that is, the variable still remembers the original value the next time the function is called. like:

<?php
function test()
{
  static $var=;
  $var+=;
  echo $var.' ';
}
test();
test();
test();
?>

The operation results are as follows:

3 5 7

One thing to note here is that the assignment operation of a variable will only be called when the variable is initialized for the first time, and this operation will not be called during the subsequent execution of the function.

Since functions in PHP are also first-class citizens, unlike C#, we can directly define functions and call them directly anywhere in the code, which is somewhat similar to JavaScript. Therefore, at this time, static function variables will be more useful than defining global variables, which can avoid conflicts caused by repeated definitions of variables. Since functions in C# cannot be directly defined and called, they must be hosted in the class. Therefore, if the function needs static variables, we only need to define them in the class to achieve the same effect.

Call method

In C#, the way we call static members is very simple and consistent, because static members do not belong to instance objects, so whether they are methods or variables, C# accesses its static members through class names, methods (variables). And in C#, static functions cannot be set as virtual methods or overridden. PHP provides more flexible and diverse support for this.

First of all, we know that in PHP, we call instance methods through: someobj->someFun(), so can we also call static functions through SomeClass->someFun() like C#? The answer is no. In PHP, calls to static members can only be made in ::, such as: SomeClass::someFun().

<?php
class TestC
{
  public static $var=;
  public $var=;
  function t()
  {
    self::$var+=;
    echo self::$var.' ';
    echo $this->var.' ';
  }
  public static function t()
  {
    self::$var+=;
    echo self::$var.' ';
  }
}
$t=new TestC();
$t->t();
TestC::t();
?>

The operation results are as follows:

3 1 5

Another difference from C# is that in the methods in the class, if we need to call static variables, we must pass the static variable self::$somVar (note that the $ symbol before the variable, the instance variable does not need it), while calling the static method is self::someFun() (the $ symbol is not needed here). As shown in the above example.

In addition, the biggest difference from C# is that in PHP, subclasses can override static functions or variables of the parent class. Not only that, (from the perspective of C# programmers, I think PHP makes things complicated). Since the default self::staticFun() calls static functions of the subclass, what should we do if we want to call static variables of the parent class at this time? Here PHP provides an additional parent to call static members of the base class. like:

<?php
class TestC
{
  public static $var=;
  public $var=;
  function t()
  {
    self::$var+=;
    echo self::$var.' ';
    echo $this->var.' ';
  }
  public static function t()
  {
    self::$var+=;
    echo self::$var.' ';
  }
}
$t=new TestC();
$t->t();
TestC::t();
?>

The operation results are as follows:

3 5 ‘Hello'

Best, based on the above example, it is easy to think that subclasses can use the parent keyword to access the parent class, so how does the parent class access the static methods of the child class? Here is another usage of static. If the scope before the called static method is replaced with static, PHP will calculate the final static method based on the inheritance level of the class. like:

<?php
class Test
{
  function t()
  {
    static::t();
  }
  public static function t()
  {
    echo self::'Test ';
  }
}
class Test extends Test
{
  static function t()
  {
    echo self::'Test ';
  }
}
$t=new Test();
$t->t();
Test::t();
?>

The operation results are as follows:

Test2 Test2

Here, when the t1 method calls the t2 static method, the final static method will be found based on its example and the output Test2 is.

Summarize

From the above analysis, it is not difficult to see that PHP provides more powerful functions or flexibility than C# for the use of static members, but from my perspective, this flexibility is not necessarily better. From a certain perspective, if the inheritance level of the class is too complex, it may confuse me. Of course, the effects of using the same tool will be completely different for different people. Since PHP provides more diverse choices, I believe that if used properly, the static in PHP may provide a more powerful and simple way to use it than in C#.