The Singleton Pattern





The Singleton Pattern is another easy design pattern. Here a simple example.

The Singleton Pattern is one of the 23 GoF patterns that are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral.

If you want to learn all about design patterns, take a look at the following book.


<?php

class Singleton
{

    
/**
     * Placeholder for the Instance of self
     * @var Singleton
     */
    
private static $instance;


    
/**
     * Class Constructor
     * @access private
     */
    
private function __construct()
    {
    }


    
/**
     * Get an instance of the singleton
     * @return Singleton
     */
    
public static function getInstance()
    {
        if (
null === self::$instance) {
            
self::$instance = new self;
        }

        return 
self::$instance;
    }


    
/**
     * Magic function for cloning
     * @acces private
     */
    
private function __clone()
    {
        throw new 
Exception('Cloning is not allowed on a singleton');
    }
}

?>
hosting nl domeinnaam checken