class Settings { private static $instance; private $settings = array(); private function __construct() {} public static function getInstance() { if(!self::$instance) { self::$instance = new Settings(); } return self::$instance; } public function set($key, $value) { $this->settings[$key] = $value; } public function get($key) { if(array_key_exists($key, $this->settings)) { return $this->settings[$key]; } return null; } } // Usage $settings = Settings::getInstance(); $settings->set('db_host', 'localhost'); echo $settings->get('db_host'); // Output: localhost
namespace App; class Settings { private static $instance; private $settings = array(); private function __construct() {} public static function getInstance() { if(!self::$instance) { self::$instance = new Settings(); } return self::$instance; } public function set($key, $value) { $this->settings[$key] = $value; } public function get($key) { if(array_key_exists($key, $this->settings)) { return $this->settings[$key]; } return null; } } // Usage use App\Settings; $settings = Settings::getInstance(); $settings->set('db_host', 'localhost'); echo $settings->get('db_host'); // Output: localhostThis example shows how to use the Singleton pattern with namespaces. The Settings class is placed in the App namespace and can be accessed in other files using the use statement.