How to create const arrays of instances of a class, within that class?
I'm creating my own PHP class. I want to have constant references within that class of instances of that class, like an enumeration.
I keep getting 2 errors: 1. Constants cannot be arrays 2. parse error at line 11 (see below)
What's wrong? Can I seriously not have a constant array? I'm from a Java background...
Here is my code:
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.");
}
$t开发者_运维问答his->name = $name;
$this->colour = $colour;
}
}
UPDATE:
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).
ORIGINAL ANSWER:
Neither arrays nor objects can be assigned to constants in PHP. The documentation says it must be a "constant expression." I don't know if they define this term, but they note it excludes, "a variable, a property, a result of a mathematical operation, or a function call. ".
It's unsurprising that constructor calls aren't allowed either, and although array
isn't really a function, it's "function-like."
Probably you'll have to do a work-around like the below. We use private static
instead of actual constants. This means you need to manually avoid re-assigning, and have to provide a getter (getClub
, etc., with naming up to you) if needed.
Also, because you can't assign an object to a static
, and PHP doesn't have static initializers, we initialize on demand in the constructor.
An unrelated issue is that you have in_array
backwards
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;
}
}
精彩评论