function get_header() {
global $config;
$header = new Template('header');
$header->set('pagetitle', $config['page_title']);
echo $header->output();
}
基本上,你在本地上下文中使用全局變量。
將配置封裝在某種Config類中,使用singleton是一個好主意,所以配置不會被任何東西覆蓋。
爲了與幾乎良好的面向對象的做法完全兼容;)
class Config {
protected $data;
public function __construct(array $config) {
$this->data = $config;
}
public function get($key) {
return $this->data['key'];
}
}
class ConfigManager {
public static $configs;
// In "good OOP" this should't be static. ConfigManager instance should be created in some kind of initialisation (bootstrap) process, and passed on to the Controller of some sort
public static function get($configName) {
if(! isset(self::$configs[$configName]))
self::$configs[$configName] = new Config(include('configs/' . $configName. '.php')); // in good OOP this should be moved to some ConfigReader service with checking for file existence etc
return self::$configs[$configName];
}
}
,然後在configs/templates.php
return array('page_title' => 'Page Title');
你的功能應該是這樣的:
function get_header() {
$config = ConfigManager::get('templates');
$header = new Template('header');
$header->set('pagetitle', $config->get('page_title'));
echo $header->output();
}
這似乎過於複雜,當然你不必遵循這種做法,但你編寫的代碼越多,你就會越喜歡良好的實踐。
使用全局變量不是其中之一!