【问题标题】:PHP Access to Undeclared Static PropertyPHP 访问未声明的静态属性
【发布时间】:2015-02-24 13:00:56
【问题描述】:

我在 PHP 中创建了一个类,但在标有星号 (*) 的行上出现致命错误(标题)

class monster{
    private $id = 0;
    private $name = "";
    private $baseLevel = 0;
    private $attack = 0;
    private $defense = 0;
    private $baseEXP = 0;
    private $dropType = 0;
    private $dropNum = 0;
    function __construct($a, $b, $c, $d, $e, $f, $g, $h){
    *   self::$id=$a;
        self::$name = $b;
        self::$baseLevel = $c;
        self::$attack = $d;
        self::$defense = $e;
        self::$baseEXP = $f;
        self::$dropType = $g;
        self::$dropNum = $h;
    }
}

我不知道是什么原因造成的,而且下面的类(同一个文件)返回了同样的错误。

class item{
    private $id = 0;
    private $name = "";
    private $type = 0; #0-weapon, 1-armor, 2-charm, 3-ability
    private $ability = 0;
    private $desc = "";
    private $cost = 0;
    function __construct($a, $b, $c, $d, $e, $f){
        self::$id=$a;
        self::$name=$b;
        self::$type=$c;
        self::$ability=$d;
        self::$desc=$e;
        self::$cost = $f;
    }
}

您是否知道导致错误的原因或我该如何解决?

【问题讨论】:

    标签: php html error-handling constructor static


    【解决方案1】:

    您应该使用关键字 static 声明您的属性,例如

    private static $id = 0;
    

    【讨论】:

      【解决方案2】:

      使用$this-> 而不是self::

      Self 用于静态成员,$this 用于实例变量。

      【讨论】:

        【解决方案3】:

        我做了这样的事情

        class A
        {
            static $A_TYPE = 'xxxx';
        
        //....
        
        // $this->type = 'xxxx'
        
        public function getStringType()
            {
               return get_class($this)::${$this->type}; 
            }
            //.....
        
         print A::$A_TYPE; 
        // xxxx
        

        【讨论】:

          猜你喜欢
          • 2017-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-18
          • 2011-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多