How to create constant arrays of class instances inside this class?

I am creating my own PHP class. I want to have permalinks in this class of instances of this class, like an enumeration.

I keep getting 2 errors: 1. Constants cannot be arrays 2. Analysis error on line 11 (see below)

What happened? Can I seriously not have a permanent array? I'm from 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.");
        }
        $this->name = $name;
        $this->colour = $colour;
    }
}
+3
source share
1 answer

UPDATE

Starting with PHP 5.6, you can determine the consttype array.

As with PHP 7.1, you can define constant visibility (before it is always public).

:

PHP. , " " . , , , ", , " .

, , array , " ".

, , . private static. , (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;
    }
}
+3

Source: https://habr.com/ru/post/1776046/


All Articles