问题描述:

I always use private $MyVar = false; when declaring private variables which only that specific class can use. But recently i saw some examples where people use private static $MyVar = false;.

I don't get it, what's the difference? Both of them can only be used inside that class, so whats the point in adding static?

网友答案:

Compare:

  1. A private instance variable named x:

    class Foo {
        private $x = 0;
        public function Foo() {
            echo ++$this->x . ',';
        }
    }
    
    new Foo();
    new Foo();
    

    The output is 1,1,.

  2. A private static variable named x:

    class Bar {
        private static $x = 0;
        public function Bar() {
            echo ++self::$x . ',';
        }
    }
    
    new Bar();
    new Bar();
    

    The output is 1,2,.

相关阅读:
Top