class Logger { private static $instance = null; private $log = array(); private function __construct() {} public static function getInstance() { if(!self::$instance) { self::$instance = new Logger(); } return self::$instance; } public function log($message) { $this->log[] = $message; } public function getLog() { return $this->log; } } // Use the Logger class $logger = Logger::getInstance(); $logger->log('An event happened'); $logger->log('Another event happened'); $log = $logger->getLog(); echo implode("\n", $log); // prints "An event happened\nAnother event happened"
class Config { private static $instance = null; private $settings = array( 'db_host' => 'localhost', 'db_user' => 'user', 'db_password' => 'password', ); private function __construct() {} public static function getInstance() { if(!self::$instance) { self::$instance = new Config(); } return self::$instance; } public function get($key) { return isset($this->settings[$key])? $this->settings[$key] : null; } } // Use the Config class $config = Config::getInstance(); echo $config->get('db_host'); // prints "localhost" echo $config->get('db_user'); // prints "user" echo $config->get('db_password'); // prints "password"This example creates a singleton Config class with a private constructor and a static getInstance method that returns the single instance of the class. The class holds the application settings in the $settings array and provides a get method to retrieve them. The package library for these examples can be any PHP package that provides singleton or static instance functionality. Some popular PHP packages for this purpose are SingletonTrait, Singleton, Pimple, and Aura.Di.