yossi
yossi

Reputation: 3164

static properties and instances

What will happen if I create a class with a static property and create two instances of it?

Will the static property be shared between both instances and not be duplicated?

Upvotes: 1

Views: 515

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163318

Yes, that is the definition of a static property.

Static properties belong to the class, not instances of the class.

class SomeClass {
   private static $instanceCount = 0;

   function __construct() {
      self::$instanceCount++;
      //do other stuff.
   }

   function instanceCount() { 
      return self::$instanceCount;
   }

}

$one = new SomeClass();
echo $one->instanceCount(); //1    

$two = new SomeClass();

echo $one->instanceCount(); //2
echo $two->instanceCount(); //2

Upvotes: 7

Related Questions