这是我的语言课。是否可以如下创建数组?我尝试过,但是我的编译器抛出错误。如果它的外部类,我可以创建该数组。但是为什么我不能在课堂上做同样的事情
不起作用
class Language{
private $LANG = array();
/*
ERROR CODE
1 DATABASE
2 EMPTY USERNAME AND PASSWORD
*/
//1 DATABASE
$LANG[1]["TITLE"] = "DATABASE CONNECTION ERROR";
$LANG[1]["MESSAGE"] = "PLEASE CONTACT YOUR ADMISTRATOR";
//2 EMPTY USERNAME AND PASSWORD
$LANG[2]["TITLE"] = "LOGIN ERROR";
$LANG[2]["MESSAGE"] = "INVALID USERNAME OR PASSWORD";
//3 EMPTY QUERY ERROR
$LANG[3]["TITLE"] = "ERROR";
$LANG[3]["MESSAGE"] = "UNABLE TO COMMUNICATE WITH SERVER";
}
有效
private $LANG = array();
/*
ERROR CODE
1 DATABASE
2 EMPTY USERNAME AND PASSWORD
*/
//1 DATABASE
$LANG[1]["TITLE"] = "DATABASE CONNECTION ERROR";
$LANG[1]["MESSAGE"] = "PLEASE CONTACT YOUR ADMISTRATOR";
//2 EMPTY USERNAME AND PASSWORD
$LANG[2]["TITLE"] = "LOGIN ERROR";
$LANG[2]["MESSAGE"] = "INVALID USERNAME OR PASSWORD";
//3 EMPTY QUERY ERROR
$LANG[3]["TITLE"] = "ERROR";
$LANG[3]["MESSAGE"] = "UNABLE TO COMMUNICATE WITH SERVER";
答案 0 :(得分:2)
首先。在方法之外的类定义中不能包含代码。您需要将其包装在方法中。
第二。如果要对类实例的属性进行操作,则必须使用this->
关键字进行指示。
因此您的代码如下所示:
class Language
{
private $LANG = array();
function __construct()
{
/*
ERROR CODE
1 DATABASE
2 EMPTY USERNAME AND PASSWORD
*/
//1 DATABASE
$this->LANG[1]["TITLE"] = "DATABASE CONNECTION ERROR";
$this->LANG[1]["MESSAGE"] = "PLEASE CONTACT YOUR ADMISTRATOR";
//2 EMPTY USERNAME AND PASSWORD
$this->LANG[2]["TITLE"] = "LOGIN ERROR";
$this->LANG[2]["MESSAGE"] = "INVALID USERNAME OR PASSWORD";
//3 EMPTY QUERY ERROR
$this->LANG[3]["TITLE"] = "ERROR";
$this->LANG[3]["MESSAGE"] = "UNABLE TO COMMUNICATE WITH SERVER";
}
function getData()
{
return $this->LANG;
}
}
$lang = new Language();
var_dump($lang->getData());
您可以在文档中进一步了解它:https://www.php.net/manual/en/language.types.object.php
编辑: 在此处进行演示https://3v4l.org/qVtD9