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

Php 用类定义信息数组的最佳方法,php,arrays,types,mapping,project,Php,Arrays,Types,Mapping,Project,我有一个数据库表,用于存储项目的“类型”,该项目存储1、2或3,其中: 1=“活动” 2=“非活动” 3=“已取消” 目前,我将此映射存储在config.php中的一个数组中,使其成为可从整个应用程序访问的全局变量。它看起来像: $project_types = array(1 => "Active", 2 => "Inactive", 3 => "Cancelled"); 现在,我有了一个项目类,它有get_type()和set_type()方法来按预期更改整数值。 我想要

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

1=“活动” 2=“非活动” 3=“已取消”

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

$project_types = array(1 => "Active", 2 => "Inactive", 3 => "Cancelled");
现在,我有了一个项目类,它有get_type()和set_type()方法来按预期更改整数值。 我想要一个get\u type\u name()方法。这里有人能解释一下这个方法应该是什么样子吗?目前,我有一些东西看起来像这样:

public function get_type_name() {
    global $project_types;
    return $project_types[$this->get_type()];
}
我认为上面的数组应该以某种方式存在于我的项目类中,但我只是不确定该走哪条路


谢谢。

全局变量不好,在您的情况下,会为您的项目类创建不必要的依赖项

解决方案(众多方案之一)非常简单:
创建一个包含类型的类属性并对其进行查找

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

}

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

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\u ACTIVE

从班级内部,或

项目::状态\u活动

从外部

并且可以使用

self::$project\u类型


我认为它会起作用,你只需将这个
get\u type\u name
函数放在
Project
类中,当你调用它时,它应该给你它的类型名。另外,你最好还是坚持Zend编码标准。。。例如,方法和属性名称应为驼峰大小写,私有/公共方法和属性应以
开头,get\u type\u name()方法如何?self::$project\u types-我想这就是我想要的,谢谢。@Justin-刚刚将它添加到project类中(假设这确实是您的project类的名称)