php - 如何像文档中那样为 Symfony 2.7 选择实现 ENUM 类?

标签 php forms symfony enums

在 Symfony 2.7 中浏览 Choice 表单字段界面的文档时,我一直注意到 top of this page 中的以下片段:

$builder->add('attending', 'choice', array(
    'choices' => array(
        Status::getInstance(Status::YES),
        Status::getInstance(Status::NO),
        Status::getInstance(Status::MAYBE),
    ),
    'choices_as_values' => true,
    'choice_label' => 'displayName',
));

Status 本质上是在 PHP 中实现一个枚举类。 Symfony 中似乎没有相应的接口(interface)。有谁知道如何优雅地实现像 Status 这样的东西,并允许在一个地方添加更多的值?

最佳答案

class Status {

    const STATUS_YES = 1;
    const STATUS_MAYBE = 2;
    const STATUS_NO = 3;

    private $enum;

    static public function getInstance($var)
    {
        return new static($var);
    }

    private function __construct($var)
    {
        $this->enum = $var;
    }

    /**
     * @returns boolean
     */
    public function is($var)
    {
        return ($this->enum == $var);
    }
}

如果你愿意,你可以使用 Status 作为一个抽象类,从这个类继承所有 Status 并返回相应的对象

关于php - 如何像文档中那样为 Symfony 2.7 选择实现 ENUM 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32326477/

相关文章:

html - 如何使这两个元素彼此相邻

php - 在 Selenium Chrome 中将语言设置为 en-UK 以进行 Behat 测试

php - 如何通过 AJAX 从 PHP 文件获取多个响应?

php - 使用多个连接进行查询

html - 表单中的 CSS 继承问题

html - 为什么 Chrome 认为我的表单是信用卡表单?

css - 应用程序/资源中的 Assets 未上课

php - 在 Symfony2 中动态导入资源到 Config.yml

PHP 引用 `$this`

php - 在哪里实现连续访问计数器?