【问题标题】:How to create const arrays of instances of a class, within that class?如何在该类中创建类实例的 const 数组?
【发布时间】:2010-11-21 06:49:55
【问题描述】:

我正在创建自己的 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;
    }
}

【问题讨论】:

  • 我也想念枚举...

标签: php arrays enums constants


【解决方案1】:

更新

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;
    }
}

【讨论】:

  • 有解决办法吗?没有这个,我的程序会相当困难 :X 而且对我来说,以任何其他方式做这件事都没有意义……那静力学呢?同样的交易?
  • 您的代码有一个无限循环。在初始化静态属性之前将 initialized 设置为 true。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 2020-03-07
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 2016-12-05
相关资源
最近更新 更多