Welcome Guest, Not a member yet? Register   Sign In
What is the best way to implement a singleton?
#1

[eluser]Xeoncross[/eluser]
I have seen many ways and I was wondering if there was a recommended way. Here are two examples.

Code:
class myclass {
    //Singleton instance object
    private static $instance;

    /**
     * Load the config values for this system
     *
     * @param array $config
     */
    public function __construct($config=null) {

        //Set singleton instance
        self::$instance =& $this;
    }
    
    /**
     * Return this classes instance
     * @return singleton
     */
    public static function &get;_instance() {
        return self::$instance;
    }
}


Code:
class myclass {

    private __construct() {/* */}
    
    /**
    * Function: current
    * Returns a singleton reference to the current connection.
    */
    public static function & current($settings = false) {
        static $instance = null;
        return $instance = (empty($instance)) ? new self($settings) : $instance ;
    }
}

Code:
class CI_Base {

    private static $instance;

    public function CI_Base()
    {
        self::$instance =& $this;
    }

    public static function &get;_instance()
    {
        return self::$instance;
    }
}

function &get;_instance()
{
    return CI_Base::get_instance();
}


With PHP 5.3 someone even started a registry styled singlton class.




Theme © iAndrew 2016 - Forum software by © MyBB