开发者

accesing static variable in php

开发者 https://www.devze.com 2023-01-09 05:53 出处:网络
i have a simple case of class with static variable and a get function all compile okbut at run time i am getting this error

i have a simple case of class with static variable and a get function all compile ok but at run time i am getting this error

[Sun Jul 25 03:57:07 2010] [error] [client 127.0.0.1] PHP Fatal error:  Undefined class constant 'TYPE' in .....

for the function getType()

here is my class

class NoSuchRequestHandler implements Handler{
    public static $TYPE  = 2001;
    public static $VER   = 0;

    public function getType(){
      return self::TYPE;
    }

  开发者_如何学C  public function getVersion(){
      return self::VER;
    }
}

thank you all


PHP thinks you're trying to access a class constant because of:

return self::TYPE;

http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php

As Chris mentions, use:

return self::$TYPE;


You can access this two ways since it is public...

class NoSuchRequestHandler implements Handler{
    public static $TYPE  = 2001;
    public static $VER   = 0;

    public function getType(){
        return self::$TYPE;  //not the "$" you were missing.  
    }

    public function getVersion(){
        return self::$VER;
    }
}

echo NoSuchRequestHandler::$TYPE; //outside of the class.


probably the confusing issue is about that a variable of non-static class

$myClass->anyVar //here there is no $ character for class variable

but for static class

MYCLASS::$anyVar  // you must use the $ char for class variable
0

精彩评论

暂无评论...
验证码 换一张
取 消