`static` keyword inside function?

后端 未结 7 2257
日久生厌
日久生厌 2020-11-28 04:46

I was looking at the source for Drupal 7, and I found some things I hadn\'t seen before. I did some initial looking in the php manual, but it didn\'t explain these examples.

相关标签:
7条回答
  • 2020-11-28 05:51

    To expand on the answer of Yang

    If you extend a class with static variables, the individual extended classes will hold their "own" referenced static that's shared between instances.

    <?php
    class base {
         function calc() {
            static $foo = 0;
            $foo++;
            return $foo;
         }
    }
    
    class one extends base {
        function e() {
            echo "one:".$this->calc().PHP_EOL;
        }
    }
    class two extends base {
        function p() {
            echo "two:".$this->calc().PHP_EOL;
        }
    }
    $x = new one();
    $y = new two();
    $x_repeat = new one();
    
    $x->e();
    $y->p();
    $x->e();
    $x_repeat->e();
    $x->e();
    $x_repeat->e();
    $y->p();
    

    outputs:

    one:1
    two:1
    one:2
    one:3 <-- x_repeat
    one:4
    one:5 <-- x_repeat
    two:2

    http://ideone.com/W4W5Qv

    0 讨论(0)
提交回复
热议问题