views:

38

answers:

1

Hi,

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

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

Thanks,

Yossi

+3  A: 

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
Jacob Relkin
great, clear answer. thanks
yossi
@yossi, Chag Sameach! :)
Jacob Relkin
toda raba, gam lecha:)
yossi