duannaxin9975 2019-07-24 00:28
浏览 153

PHP类常量为Enums

Using class constants in PHP, is it possible to enforce that an argument must be one of the constants (like an Enum)?

Class Server {
    const SMALL = "s";
    const MEDIUM = "m";
    const LARGE = "l";

    private $size;

    public function __construct($size) {
        $this->size = $size
    }
}

$small = new Server(Server::SMALL); // valid
$foobar = new Server("foobar");      // also valid. This should fail instead

The case of new Server("foobar") should fail, but because the constructor does not validate $size this works. For brevity I only listed three constant sizes, but assume there are N number of sizes so don't want to do a big block of if checks.

  • 写回答

2条回答 默认 最新

  • duannian4784 2019-07-24 00:31
    关注

    Consider using the myclabs/php-enum package, which provides the functionality you are looking for.

    If you try to pass an invalid enum value, an exception will be thrown.

    Package docs: https://github.com/myclabs/php-enum#documentation

    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法