Analysis of the use of static variables and static variables in PHP

Source: Internet
Author: User
This article mainly on the static variables in PHP and static variables used to explain the use of the relevant information, the need for friends can refer to the following

Static variables exist only within the scope of the function, that is, the static variables only live in the stack. General function variables are released after the function ends, such as local variables, but static variables do not. That is, the value of the variable is preserved the next time the function is called.

As long as the variable is preceded by the keyword static, 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 Run Result:

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

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

Program List: Static members of a 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 the scope-scoped operator, where the self-scope is used instead of the $this scope, $this scope represents only the current instance of the class, and a: 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 Run Result:

Program List: Static properties

<?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 the qualifying operator  print Nowamagic:: $nm. "<br/>";  Method of calling class  $nowamagic = new Nowamagic ();  Print $nowamagic->nmmethod (). "<br/>";  Print article:: $nm. "<br/>";  $nmArticle = new article ();  Print $nmArticle->nmmethod (). "<br/>";? >

Program Run Result:

Program List: A simple static constructor

PHP does not have a static constructor, you may need to initialize the static class, and there is a very simple way to call the demonstration () method of the class directly after the class definition.

<?phpfunction 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 are the static constructor    //because in a function, everything I s allowed, including initializing using other functions self    :: $MyStaticVar = demonstration ();  }} Mystaticclass::mystaticinit (); Call the static Constructorecho Mystaticclass:: $MyStaticVar,//this is the result of the demonstration ()?>

Program Run Result:

This is the result of demonstration ()

The following is a description of the use of static variables in PHP

The static keyword is very common in C # programming, and it is used to declare static members that belong to the type itself rather than to a particular object. The static modifier can be used for classes, fields, methods, properties, operators, events, and constructors, but not for types other than indexers, destructors, or classes. Classes, functions, and variables declared as static will not be able to reference instance methods or variables, and in C # Once the class has been added with the static modifier, all of its internal variables and methods must be static. Static variables and methods must be referenced through the class name and not through the instance object.

So what's the difference between the static keyword and C # in PHP?

Declaration scope

Compared to C #, the use of static variables in PHP is more extensive, we can not only add static modifiers to the class, method, or variable, we can even add the static keyword to the function's internal variables. A variable with the static modifier added is not lost even after the function has finished executing, that is, the variable remembers the original value the next time the function is called. Such as:

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

The results of the operation are as follows:

3 5 7

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

Since functions in PHP are also class-one citizens, unlike C #, we can directly define functions and invoke them directly anywhere in the code, which is somewhat similar to JavaScript. So this time the function static variable is more useful than defining a global variable, which avoids duplicate definitions of variables that cause conflicts. Because functions in C # cannot be directly defined and called, it must be hosted in a class, so if a function requires a static variable, we only need to define it in the class to achieve the same effect.

Invocation mode

In C #, we call static members in a very simple and consistent way, because static members are not part of an instance object, so either a method or a variable, C # accesses its static members through the class name. Method (variable). And in C #, static functions cannot be set to virtual methods or overwritten. PHP provides a more flexible and versatile support for this.

First of all, we know that invoking instance methods in PHP is called by Someobj->somefun (), so can we call a static function to call it through Someclass->somefun () like C #? The answer is no, in PHP, the call to a static member can only be done by:: Someclass::somefun ().

<?phpclass 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 results of the operation are as follows:

3 1 5

Another point that differs from C # is that in a method in a class, if we need to invoke a static variable, we must pass self: $somVar static variable (note that the $ symbol before the variable, the instance variable is not required), and the static method is called Self::somefun () (This does not require the $ symbol). As in the above example.

In addition, the biggest difference with C # is that in PHP, subclasses can override the parent class's static function or variable, not only that, (from the perspective of the C # Programmer, I think the PHP point is complicated), because the default Self::staticfun () call is a subclass of the static function , what if we want to invoke the static variables of the parent class? Here PHP provides an additional parent to invoke the static members of the base class. Such as:

<?phpclass 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 results of the operation are as follows:

3 5 ' Hello '

Best of all, according to the above example, it is easy to think that the subclass access parent class can use the parent keyword, then how does the parent class access the static method of the subclass? Here's another way to use static, where if you change the scope of the preceding static method to static, PHP calculates the final static method based on the class's inheritance hierarchy. Such as:

<?phpclass 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 results of the operation are as follows:

Test2 Test2

Here the T instance finds the final static method and outputs Test2 based on its instance when the T1 method invokes the T2 static method.


From the above analysis, it is not difficult to see that, for the use of static members, PHP provides more powerful than C # functionality or flexibility, but from my point of view, this flexibility is not necessarily better, from a certain point of view, if the class inheritance hierarchy is too complex, it may confuse me. Of course, the same tool will work differently for different people, since PHP offers a more diverse selection, then believe that if used properly, the static in PHP may provide a more powerful and easy way to use than in C #.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.