Jus*_*tin 0 php arrays mapping types project
我有一个数据库表,存储项目的"类型",存储1,2或3,其中:
1 ="有效"2 ="无效"3 ="已取消"
目前,我将此映射存储在config.php中的数组中,使其成为可从我的整个应用程序访问的全局变量.它看起来像:
$project_types = array(1 => "Active", 2 => "Inactive", 3 => "Cancelled");
Run Code Online (Sandbox Code Playgroud)
现在,我有一个Project类,它有get_type()和set_type()方法来按预期更改整数值.我想要一个get_type_name()方法.这里的任何人都可以解释这个方法应该是什么样子 目前,我有一些看起来像这样的东西:
public function get_type_name() {
global $project_types;
return $project_types[$this->get_type()];
}
Run Code Online (Sandbox Code Playgroud)
我上面的数组应该以某种方式存在于我的Project类中,但我只是不确定要采取什么路由.
谢谢.
全局变量很糟糕,在您的情况下,会为您的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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |