我正在创建自己的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;
}
}
答案 0 :(得分:3)
<强>更新强>:
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表示它必须是“常量表达”。我不知道他们是否定义了这个术语,但他们注意到它排除了“变量,属性,数学运算的结果或函数调用。”。
不允许构造函数调用也不足为奇,虽然array
实际上不是函数,但它的功能类似于函数。
可能你必须像下面那样进行解决。我们使用private static
而不是实际常量。这意味着您需要手动避免重新分配,并且必要时必须提供一个getter(getClub
等,并命名最多)。
另外,因为您无法将对象分配给static
,并且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;
}
}