【问题标题】:accesing static variable in php在php中访问静态变量
【发布时间】:2010-07-25 01:04:43
【问题描述】:

我有一个带有静态变量和 get 函数的类的简单案例 一切编译正常,但在运行时我收到此错误

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

对于函数getType()

这是我的课

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

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

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

谢谢大家

【问题讨论】:

    标签: php function static getter


    【解决方案1】:

    PHP 认为您正在尝试访问类常量,因为:

    return self::TYPE;
    

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

    正如克里斯所说,使用:

    return self::$TYPE;
    

    【讨论】:

    • 我认为您更好地指出了这里的错误是什么。谢谢它也帮助了我:)
    【解决方案2】:

    你可以通过这两种方式访问​​它,因为它是公开的......

    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.
    

    【讨论】:

      【解决方案3】:

      可能令人困惑的问题是关于非静态类的变量

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

      但对于静态类

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-19
        • 1970-01-01
        • 2015-07-22
        • 2012-06-29
        相关资源
        最近更新 更多