PHP 访问未声明的静态属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27670284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:28:13  来源:igfitidea点击:

PHP Access to Undeclared Static Property

phphtmlerror-handlingconstructorstatic

提问by Yaakov Schectman

I've made a class in PHP and I'm getting a Fatal Error(Title) on the line marked with an asterisk(*)

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

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;
    }
}

I can't figure out what's causing it, also, the following class(same file) is returning the same error.

我无法弄清楚是什么导致了它,而且,以下类(同一文件)返回相同的错误。

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;
    }
}

Do you happen to know what's causing the error or how I can fix it?

您是否知道导致错误的原因或我如何修复它?

回答by Dmitri Kadykov

You should declare your properties with keyword static, e.g.

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

static private $id = 0;

回答by Ryan Printup

Use $this->instead of self::

使用$this->代替self::

Selfis for static members and $thisis for instance variables.

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