HalfWebDev
HalfWebDev

Reputation: 7638

Unable to get Static declaration behaviour in PHP

    class StaticTester
   {
      private static $id=0;
      function__construct()
     {
          self::$id+=1;
     }
    public static function checkIdFromStaticMethod()
   {
      echo "Current Id from Static method is ".self::$id;
    }


 }

  $st1=new StaticTester();
 StaticTester::checkIdFromStaticMethod();       // this outputs 1.

Okay ,I am not getting why the output is 1? After all Static means the value cannot be changed !

Upvotes: 0

Views: 100

Answers (5)

dweeves
dweeves

Reputation: 5605

static means : for all possible instances, the same variable will be used

   function__construct()
     {
          self::$id+=1;
     }

 $st1=new StaticTester();

when doing the new , __construct is called , so your $id static variable will be used & increased. may you do $st2=new StaticTester() , StaticTester::checkIdFromStaticMethod() will return 2 !!! That's what your code is meant to do as it is written.

Agree with "constant" answers.

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88647

Static does not mean that the value cannot be changed, it means that the value is held at the class level and not at the instance level. Other languages (such as Java) sometimes refer to this as a "class variable".

I think you are getting confused between static and final or const.

Manual refs:

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

static does not mean the value cannot be changed at all! You want const, or final (which PHP does not have). static will actually retain the value between method calls (since it's a member, it would anyway).

Upvotes: 0

davogotland
davogotland

Reputation: 2777

function__construct()
{
    self::id+=1;
}

should be

function__construct()
{
    self::$id+=1;
}

missed a dollar sign there :)

oops.... misread the question. i thought you had an error in your code hehe. which you did, but probably just a copy/paste error.

it becomes one since it's incremented by one each time a new object is created. and all the objects share the same id variable. this is what static means.

a number that can never change is called a constant, and declared with the keyword const in php.

Upvotes: 1

Wrikken
Wrikken

Reputation: 70460

No, static means without instance, you are probable looking for constants.

Upvotes: 2

Related Questions