我有一个数组,其中包含我的类以外的配置数据,并且在我的类中通常需要来自此数组的值。在我班上获得这些价值的最简洁方法是什么?
<?
$config["deco"] = "dark";
class Car {
private $color;
public function getColor() {
return $this->color;
}
public function setColor($color) {
$this->color = $config["deco"].' '.$color;
// here I need a value from $config
}
public function __toString() {
return "My car is ".$this->getColor()."\n";
}
}
$car = new Car();
$car->setColor("blue");
echo $car; // "My car is dark blue";
答案 0 :(得分:2)
这是你想要的吗?
$config = array('deco' => 'foo', …
$car = new Car();
$car->setColor($config['deco'] . 'blue');
echo $car; // My car is fooblue
class Car {
private $color;
public function getColor() {
return $this->color;
}
public function setColor($color) {
$this->color = $color;
}
public function __toString() {
return "My car is ".$this->getColor()."\n";
}
}
答案 1 :(得分:1)
两种方法 - 您可以在需要配置的函数中使用global关键字:
public function setColor($color) {
global $config;
$this->color = $config["deco"].' '.$color;
// here I need a value from $config
}
或者,我首选的方法是将配置作为静态可用值的类:
$config["deco"] = "dark";
class Config
{
static $values = array(
"deco" => "dark",
);
public static function get($name)
{
if (isset(self::$values[$name])) {
return self::$values[$name];
}
return null;
}
}
class Car {
private $color;
public function getColor() {
return $this->color;
}
public function setColor($color) {
$this->color = Config::get("deco").' '.$color;
// here I need a value from $config
}
public function __toString() {
return "My car is ".$this->getColor()."\n";
}
}
我实际上将所有配置都放在ini类型的文件中 - 并且Config类解析该ini文件以构建数据数组,然后像上面那样进行访问...但我把它作为练习留给读者< / p>
答案 2 :(得分:0)
我最喜欢的是Dependency-Injection http://components.symfony-project.org/dependency-injection/trunk/book/01-Dependency-Injection
答案 3 :(得分:0)
您的配置选项在您的应用程序中将是唯一的,因此在某处应该只有1个副本。
如果你在全局范围内包含一个包含$config
数组的文件,那么在类中使用$GLOBALS['config']["deco"]
的最脏(也是最快)的方法就是这样。
但是,您可能会发现将配置值封装在类中更有用,可以作为静态变量:
class Config {
public static $config = array(
'deco' => 'dark'
) ;
}
随后您可以将其作为Config::$config['deco']
或Singleton类访问:
class Config {
private static $_instance = null ;
public $config = array(
'deco' => 'dark'
) ;
public static function getInstance() {
if (self::$_instance == null || !self::$_instance instanceOf Config) {
self::$_instance = new Config() ;
}
return self::$_instance ;
}
}
然后使用Config::getInstance()->config["deco"]
通过这两种方式,您可以灵活地构建获取,存储,缓存配置值以及防御性编码的功能,方法是在尝试访问它时确保配置值实际存在,返回默认值等。您还可以ofcourse为类添加函数以使“get”语法更短。