Usage of static and static variables in PHP

Source: Internet
Author: User
This article mainly describes the usage of static and static variables in PHP. For more information, see

This article mainly describes the usage of static and static variables in PHP. For more information, see

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 n1_hod () {self: $ nm + =; echo self: $ nm .'
';}}$ NmInstance = new nowamagic (); $ nmInstance-> n1_hod (); $ nmInstance = new nowamagic (); $ nmInstance-> n1_hod ();?>

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:




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 functionsself: $ 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 ();?>

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.

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.