Friday, January 13, 2012

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 !

5 comments:

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

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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).

    ReplyDelete
  4. 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:


    static keyword
    final keyword
    Class constants

    ReplyDelete
  5. 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.

    ReplyDelete