美文网首页
static 关键字

static 关键字

作者: Leonzai | 来源:发表于2018-05-16 14:42 被阅读9次

    静态变量

    最基本的知识

    function test()
    {
        static $a = 0;
        echo $a;
        $a++;
    }
    
    /**
    如果没有 static 关键字,在第一次运行完 test 函数的时候,$a 就被销毁了。
    第二次运行函数时候,会被重新赋值为 0 。
    
    存在 static 关键字,第一次运行完函数,$a 的值并不会被销毁。
    第二次运行函数的时候,会去内存 static 区域中查找 $a 是否存在,存在就不再赋值了。
    */
    

    连续声明会报错

    <?php
    function foo(){
        static $int = 0;          // correct
        static $int = 1+2;        // wrong  (as it is an expression)
        static $int = sqrt(121);  // wrong  (as it is an expression too)
    
        $int++;
        echo $int;
    }
    

    后期静态绑定

    <?php
    class a{
        static protected $test="class a";
    
        public function static_test(){
            echo static::$test; // Results class b
            echo self::$test; // Results class a
        }
    }
    
    class b extends a{
        static protected $test="class b";
    }
    
    $obj = new b();
    $obj->static_test();
    
    <?php
    class A {
        public static function who() {
            echo __CLASS__;
        }
        public static function test() {
            self::who();      // A
            static::who();    // B
        }
    }
    
    class B extends A {
        public static function who() {
            echo __CLASS__;
        }
    }
    
    B::test();
    

    理解继承

    <?php
    class A {
        private function foo() {
            echo "success!\n";
        }
        public function test() {
            $this->foo();
            static::foo();
        }
    }
    
    class B extends A {
       /* foo() will be copied to B, hence its scope will still be A and
        * the call be successful */
    }
    
    class C extends A {
        private function foo() {
            /* original method is replaced; the scope of the new one is C */
        }
    }
    
    $b = new B();
    $b->test();             // success success
    $c = new C();
    $c->test();         // success 不能再 A 中访问 C 的私有方法
    

    复杂的例子

    
    <?php
    class A {
        public static function foo() {
            static::who();
        }
    
        public static function who() {
            echo __CLASS__."\n";
        }
    }
    
    class B extends A {
        public static function test() {
            A::foo();
            parent::foo();
            self::foo();
        }
    
        public static function who() {
            echo __CLASS__."\n";
        }
    }
    class C extends B {
        public static function who() {
            echo __CLASS__."\n";
        }
    }
    
    C::test();
    
    // 输出 ACC
    // 总结,无论在静态绑定前调用的是 self,parent,还是什么乱七八糟的,最终返回的都是一开始调用的 类。
    

    总结,无论在静态绑定前调用的是 self,parent,还是什么乱七八糟的,最终返回的都是一开始调用的 类。

    相关文章

      网友评论

          本文标题:static 关键字

          本文链接:https://www.haomeiwen.com/subject/mvepdftx.html