使用类定义信息数组的最佳方法

时间:2011-04-01 21:31:20

标签: php arrays types mapping project

我有一个数据库表,用于存储项目的“类型”,该项目存储1,2或3,其中:

1 =“有效” 2 =“无效” 3 =“已取消”

目前,我将此映射存储在config.php中的数组中,使其成为可从我的整个应用程序访问的全局变量。它看起来像:

$project_types = array(1 => "Active", 2 => "Inactive", 3 => "Cancelled");

现在,我有一个Project类,它有get_type()和set_type()方法来按预期更改整数值。 我想要一个get_type_name()方法。这里的任何人都可以解释这个方法应该是什么样子目前,我有一些看起来像这样的东西:

public function get_type_name() {
    global $project_types;
    return $project_types[$this->get_type()];
}

我上面的数组应该以某种方式存在于我的Project类中,但我不确定要采取什么路径。

感谢。

2 个答案:

答案 0 :(得分:5)

全局变量很糟糕,在您的情况下,会为您的Project类创建不必要的依赖项。

解决方案(众多问题之一)非常简单:
创建一个包含类型并在其上执行查找的类属性。

class Project {

    /**
     * @param array Holds human translations of project types.
     */
    protected $_types = array(
        1 => 'Active',
        2 => 'Inactive',
        3 => 'Cancelled',
    );

    /**
     * Get a human-readable translation of the project's current type.
     *
     * If a translation can't be found, it returns NULL.
     *
     * @return string|null
     */
    public function get_human_type() {
        $type = $this->get_type();
        return isset($this->_types[$type]) ? $this->_types[$type] : NULL;
    }

}

答案 1 :(得分:4)

就个人而言,我将它声明为静态类属性,可能使用不同值的类常量:

class Project
{
    /**    constants */
    const STATUS_ACTIVE         = 'Active';
    const STATUS_INACTIVE       = 'Inactive';
    const STATUS_CANCELLED      = 'Cancelled';

    protected static $projectTypes    = array( 1 => self::STATUS_ACTIVE,
                                               2 => self::STATUS_INACTIVE,
                                               3 => self::STATUS_CANCELLED
                                             );

    public function getTypeName() {
        return self::$projectTypes[$this->get_type()];
    } 

}

可以使用

访问这些常量
  

self :: STATUS_ACTIVE

来自班级,或

  

项目:: STATUS_ACTIVE

来自外部;

可以使用

访问数组
  

自:: $ project_types

相关问题