Thread: PHP Login Class
View Single Post
Old 05-23-2009, 02:25 AM   #39 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

You could, if you think it warrants it, convert the class to a singleton. I doubt you're going to want more than one instance of the login class, and so it does make sense to convert it to a singleton class as shown below.

I am not a lover of making all the functions static because you get rid of the ability to have member functions, saved states, and all the other OOP features. I use static functions as namespaces. Now that the new version of PHP will have namespaces, I doubt I'll be using static functions ever again.

When I say static functions, you will need one to make the singleton work, and this is more than fine. The getInstance function returns the object. By setting the constructor to private you're unable to initiate the class by using new.

php Code:
class TalkPHP_Singleton
{
    private static $m_pInstance;
    private $m_szHello;
   
    /* Prevent external initiation but still called. */
    private function __construct()
    {
        $this->m_szHello = 'Hello';
    }
   
    /**
     * @return TalkPHP_Singleton
     */

    public static function getInstance()
    {
        if (empty(self::$m_pInstance))
        {
            /* self() being this class we're in. */
            self::$m_pInstance = new self();
        }
       
        return self::$m_pInstance;
    }
   
    public function getHello($szName)
    {
        return sprintf('Hello %s!', $szName);
    }
}

echo TalkPHP_Singleton::getInstance()->getHello('Adam');
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote