我正在创建自己的PHP类.我想在该类实例的该类中拥有常量引用,例如枚举.
我不断收到2个错误:
1.常量不能是数组
2.在第11行解析错误(请参见下文)
怎么了?我可以严重地没有常量数组吗?我来自Java背景…
这是我的代码:
class Suit {
const SUIT_NAMES = array("Club", "Diamond", "Heart", "Spade");
const COLOURS = array("red", "black");
const CLUB = new Suit("Club", "black"); // LINE 11
const DIAMOND = new Suit("Diamond", "red");
const HEART = new Suit("Heart", "red");
const SPADE = new Suit("Spade", "black");
var $colour = "";
var $name = "";
function __construct($name, $colour) {
if (!in_array(self::SUIT_NAMES, $name)) {
throw new Exception("Suit Exception: invalid suit name.");
}
if (!in_array(self::COLOURS, $colour)) {
throw new Exception("Suit Exception: invalid colour.");
}
$this->name = $name;
$this->colour = $colour;
}
}
解决方法:
更新:
As of PHP 5.6 it’s possible to define a const
of type array
.
Also as of PHP 7.1 it’s possible to define constant visibility (before it would always be public).
原始答案:
数组和对象都不能分配给PHP中的常量. documentation说它必须是“常量表达式”.我不知道他们是否定义了该术语,但他们注意到它不包括“变量,属性,数学运算结果或函数调用.”.
毫不奇怪,也不允许构造函数调用,尽管数组并不是真正的函数,但它是“类似函数的”.
可能您需要像下面这样解决.我们使用私有静态代替实际的常量.这意味着您需要手动避免重新分配,并且如果需要,必须提供一个吸气剂(getClub等,由您自己命名).
另外,由于您不能将对象分配给静态对象,并且PHP没有静态初始化程序,因此我们可以根据需要在构造函数中进行初始化.
一个不相关的问题是您的in_array向后
class Suit {
private static $CLUB, $DIAMOND, $HEART, $SPADE;
private static $SUIT_NAMES = array("Club", "Diamond", "Heart", "Spade");
private static $COLOURS = array("red", "black");
private static $initialized = false;
function __construct($name, $colour) {
if(!self::$initialized)
{
self::$CLUB = new Suit("Club", "black");
self::$DIAMOND = new Suit("Diamond", "red");
self::$HEART = new Suit("Heart", "red");
self::$SPADE = new Suit("Spade", "black");
self::$initialized = true;
}
if (!in_array($name, self::$SUIT_NAMES)) {
throw new Exception("Suit Exception: invalid suit name.");
}
if (!in_array($colour, self::$COLOURS)) {
throw new Exception("Suit Exception: invalid colour.");
}
$this->name = $name;
$this->colour = $colour;
}
}