PHP static variables and static variables use details, static use details _ PHP Tutorial

Source: Internet
Author: User
The use of static and static variables in PHP is detailed, and the use of static variables is detailed. The use of static and static variables in PHP is explained in detail. the use of static variables only exists in the function scope, that is, static variables only survive in the stack. Common functions: PHP static variables and static variables

Static variables only exist in the function scope. that is to say, static variables only exist in the stack. Generally, variables in a function are released after the function ends, such as local variables, but static variables do not. That is to say, when you call this function again, the value of this variable will be retained.

As long as the keyword static is added before the variable, the variable becomes a static variable.

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

Program running result:
1
2
2
4
3
8

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

Static attributes 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, rather than to an instance of the class. This variable is valid for all instances.

: It is a scope-limited operator. here, the self scope is used, instead of $ this scope. $ this scope only indicates the current instance of the class, and self: indicates the class itself.

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

Program running result:
1
3
2
5

Program List: Static attribute

<? Php class NowaMagic {public static $ nm = 'www .nowamagic.net '; public function n1_hod () {return self: $ nm ;}} class Article extends NowaMagic {public function articleMethod () {return parent: $ nm ;}/// the static variable print NowaMagic: $ nm is accessed by using the limitation operator."
"; // Call the class method $ nowamagic = new NowaMagic (); print $ nowamagic-> n1_hod ()."
"; Print Article: $ nm ."
"; $ NmArticle = new Article (); print $ nmArticle-> n1_hod ()."
";?>

Program running result:

Www.nowamagic.net
Www.nowamagic.net
Www.nowamagic.net
Www.nowamagic.net

Program List: a simple static constructor

PHP does not have a static constructor. you may need to initialize a static class. there is a very simple method that directly calls the Demonstration () method of the class 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 is the static constructor    //because in a function, everything is allowed, including initializing using other functions    self::$MyStaticVar = Demonstration();  }} MyStaticClass::MyStaticInit(); //Call the static constructorecho MyStaticClass::$MyStaticVar;//This is the result of demonstration()?>

Program running result:

This is the result of demonstration ()

The following describes how to use static PHP static variables.

Static keywords are very common in C # programming. they are used to modifier declarations that belong to types rather than static members of specific objects. Static modifiers can be used for classes, fields, methods, attributes, operators, events, and constructors, but cannot be used for types other than the indexer, destructor, or class. Classes, functions, and variables declared as static cannot reference instance methods or variables. In addition, once the class is added with a static modifier in C, all internal variables and methods must be static. Static variables and methods must be referenced by class names instead of instance objects.

So what are the differences between static keywords in php and C?

Declaration scope

Compared with C #, PHP uses a wider range of static variables. we can not only add static modifiers before classes, methods, or variables, we can even add the static keyword to the variable inside the function. The variable with the static modifier is not lost even after the function is executed. that is to say, the variable still remembers the original value when the function is called the next time. For example:

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

The running result is as follows:

3 5 7

Note that the value assignment operation of a variable will only be called during the first initialization of the variable. this operation will not be called during subsequent function execution.

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

Call method

In C #, the method for calling static members is very simple and consistent, because static members do not belong to instance objects, so whether it is a method or a variable, C # access to its static members is by class name. method (variable. In C #, static functions cannot be set as virtual methods or overwritten. PHP provides more flexible and diverse support.

First, we know that PHP calls the instance method through someobj-> someFun (), so can we call static functions through SomeClass-> someFun () like C () what about calling? The answer is No. in PHP, the call to static members can only be done through:, for example, 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 running result is as follows:

3 1 5

Another difference from C # is that in methods in the class, if we need to call static variables, we must use the self: $ somVar static variable (note the $ symbol before the variable, instance variables are not required), while static methods are called as self: someFun () ($ is not required here ). For example.

In addition, the biggest difference with C # is that in PHP, subclasses can cover static functions or variables of the parent class. (from the perspective of C # programmers, I think PHP makes things complicated.) the default self: staticFun () calls the static function of the subclass, what if we want to call the static variables of the parent class at this time? Here, PHP provides additional parents to call static members of the base class. For example:

<?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 running result is as follows:

3 5 'Hello'

It is best that, based on the above example, we can easily think that the child class can use the parent keyword to access the parent class. how can the parent class access the static method of the child class? Here is another usage of static. if the scope before the called static method is changed to static, PHP calculates the final static method based on the inheritance hierarchy of the class. For example:

<?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 running result is as follows:

Test2 Test2

Here, t instance finds the final static method based on its instance and outputs test2.

Summary

From the above analysis, we can easily see that for the use of static members, PHP provides more powerful functions or flexibility than C #, but from my perspective, this flexibility is not necessarily better. from a certain perspective, if the inheritance hierarchy of the class is too complex, it may confuse me. Of course, the use of the same tool will be totally different for different people. since PHP provides more diverse options, I believe that if appropriate, static in PHP may provide more powerful and easy-to-use methods than in C.

The distinct static variable only exists in the function scope, that is, the static variable only exists in the stack. General functions...

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: info-contact@alibabacloud.com 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.