Singleton Pattern on PHP

Concept: A creational pattern. You basically need one "global-type" object to exist. Implementation is pretty cut-and-dry using PHP.

Pros: We can be sure that there is only one access point to the class.

Cons: Anything "global in nature" leads to tightly coupled classes. We want loosely coupled classes. Unit testing individual classes becomes more difficult.

PHP: Singleton Logger



namespace JustinBellamyCom\Util\Logging;

class LoggerSingleton {  
    private static $instance;
    private $log;

    public static function getInstance()
        if(null === static::$instance) {
            static::$instance = new static(); //late static binding (since PHP 5.3.0)
        return static::$instance;

    // prevent creating a new instance
    private function __construct(){
        $this->log = array();

    //prevent cloning/duplicates
    private function __clone(){}
    private function __wakeup(){}

    //write to log
    public function log($msg)
            $this->log[] = $msg;

    //retrieve log
    public function getLog()
           return $this->log;


//composer autoloader
require_once __DIR__.'/vendor/autoload.php';

use JustinBellamyCom\Util\Logging\LoggerSingleton;

$l = LoggerSingleton::getInstance();
$l->log('Log entry one.');
$l->log('Log entry two.');

Source Code on GitHub: