My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.
PHP CODE EXAMPLE created on Sunday, October 03, 2010 permalink
How to create a singleton in PHP
This example shows the syntax of creating a singleton in PHP. Note that the instance of the class is retrieved twice but its internal variable was set only once which shows that the same instance of the class is being retrieved and not being created again each time it is needed. Use this for any kind of global scope you need in your application, especially classes which have expensive initializations such as retrieving and parsing large amounts of data to be used by various classes in your application.
<?php
echo 'printed at ' . qdat::getMilliseconds() . '<br/>';
$datapodManager = DatapodManager::getInstance();
echo $datapodManager->getTitle() . '<hr/>';


echo 'printed at ' . qdat::getMilliseconds() . '<br/>';
$datapodManager = DatapodManager::getInstance();
echo $datapodManager->getTitle() . '<hr/>';


class DatapodManager {

    protected $title;
    public function getTitle() { return $this->title; }
    
    private static $instance;
    private function __construct() {
        $this->title = 'title set internally at ' . qdat::getMilliseconds();
    }
    
    public static function getInstance(){
        if(!isset(self::$instance)) {
            self::$instance = new DatapodManager();
        }
        return self::$instance;
    }
}

class qdat {
    public static function getMilliseconds() {
        $millisecondsParts = explode ( ' ', microtime () );
        $fraction = $millisecondsParts[0];
        $milliseconds = $fraction * 1000000;
        return $milliseconds;
    }
}
?>
need markup?