note 92085 modified in function.parse-ini-file by danbrown

From: Date: Wed, 08 Jul 2009 15:26:08 +0000
Subject: note 92085 modified in function.parse-ini-file by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-158068@lists.php.net to get a copy of this message
Here's a simple settings class that parses an ini file for settings. It has a private constructor so that it can only be instantiated through the getInstance method, this means that there can only ever be one settings object at a time. <?php class Settings { private static $instance; private $settings; private function __construct($ini_file) { $this->settings = parse_ini_file($ini_file, true); } public static function getInstance($ini_file) { if(! isset(self::$instance)) { self::$instance = new Settings($ini_file); } return self::$instance; } public function __get($setting) { if(array_key_exists($setting, $this->settings)) { return $this->settings[$setting]; } else { foreach($this->settings as $section) { if(array_key_exists($setting, $section)) { return $section[$setting]; } } } } } ?> settings.ini [General] url = "http://www.example.com" [Database] host = localhost username = user password = password db = cms adapter = mysqli Using the class <?php $settings = Settings::getInstance(/*path to settings.ini*/); echo $settings->url; print_r($settings->Database); echo $settings->db; ?> Output would be: http://www.example.com Array ( [host] => localhost [username] => user [password] => password [db] => cms [adapter] => mysqli ) cms --was-- Here's a simple settings class that parses an ini file for settings. It has a private constructor so that it can only be instantiated through the getInstance method, this means that there can only ever be one settings object at a time. <?php class Settings { private static $instance; private $settings; private function __construct($ini_file) { $this->settings = parse_ini_file($ini_file, true); } public static function getInstance($ini_file) { if(! isset(self::$instance)) { self::$instance = new Settings($ini_file); } return self::$instance; } public function __get($setting) { if(array_key_exists($setting, $this->settings)) { return $this->settings[$setting]; } else { foreach($this->settings as $section) { if(array_key_exists($setting, $section)) { return $section[$setting]; } } } } } ?> settings.ini [General] url = "http://www.somesite.com" [Database] host = localhost username = user password = password db = cms adapter = mysqli Using the class <?php $settings = Settings::getInstance(/*path to settings.ini*/); echo $settings->url; print_r($settings->Database); echo $settings->db; ?> Output would be: http://www.somesite.com Array ( [host] => localhost [username] => user [password] => password [db] => cms [adapter] => mysqli ) cms http://php.net/manual/en/function.parse-ini-file.php

« previous php.notes (#158068) next »