singleton class (php5 - taking care of clone method)

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

singleton class (php5 - taking care of clone method)

Post by timvw »

I forgot i wrote this a few days ago...
Will trigger an error if someone tries to clone the object (bypassing the essence of this class).

Code: Select all

<?php

// +----------------------------------------------------------------------------
// | Author: Tim Van Wassenhove <timvw@users.sourceforge.net>
// | Update: 2005-01-22 07:11
// |
// | A singleton class.
// +----------------------------------------------------------------------------


class Singleton
&#123;
    private static $singleton;
    
    private function __construct()
    &#123;
        echo "inside constructor method.";
    &#125;
    
    public static function getInstance()
    &#123;
        if (self::$singleton == null)
        &#123;
            self::$singleton = new Singleton;
        &#125;
        return self::$singleton;
    &#125;
    
    public function __clone()
    &#123;
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    &#125;
&#125;

$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
$instance3 = clone($instance1);
?>

feyd | fixed spelling error in function call example.
Post Reply