PHP static static variables

巴扎黑
Release: 2016-11-09 14:18:26
Original
1211 people have browsed it

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

As long as you add the keyword static before a variable, the variable becomes a static variable.

    <?php    
        function test()    
       {    
            static $nm = 1;    
            $nm = $nm * 2;    
            print $nm."<br />";    
        }    
    
        // 第一次执行,$nm = 2    
        test();    
        // 第一次执行,$nm = 4    
        test();    
        // 第一次执行,$nm = 8    
        test();    
    ?>
Copy after login

Program running results:

2 4

8

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

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

Program List: Static members 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 the scope limiting operator. The self scope is used here instead of the $this scope. The $this scope only represents the current instance of the class, and self:: represents the class itself.

view source

print?

 <?php    
        class nowamagic    
        {    
            public static $nm = 1;    
    
            function nmMethod()    
            {    
                self::$nm += 2;    
                echo self::$nm . &#39;<br />&#39;;    
            }    
        }    
   
        $nmInstance1 = new nowamagic();    
        $nmInstance1 -> nmMethod();    
    
        $nmInstance2 = new nowamagic();    
        $nmInstance2 -> nmMethod();    
    ?>
Copy after login

Program running result:

3

5

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!