-3

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?

Adrao
  • 412
  • 5
  • 18
  • 1
    A `static` class property is always the same value for all instances of the class, and even exists if there are no instances (when it can be accessed from static methods) - [PHP Docs](http://www.php.net/manual/en/language.oop5.static.php) It has no connection with visibility (private/public/protected) at all – Mark Baker Aug 24 '14 at 13:49
  • I found the answer here http://stackoverflow.com/questions/1957629/how-to-access-a-private-member-inside-a-static-function-in-php?rq=1 – Adrao Aug 24 '14 at 13:59
  • 2
    Please post answers as answers and not as comments. – zsawyer Aug 24 '14 at 14:02

1 Answers1

0

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,.

Boann
  • 48,794
  • 16
  • 117
  • 146