You are not logged in.
- Topics: Active | Unanswered
#1 2010-01-04 12:32:23
- frozen_space
- Member

- From: Wuxi, China
- Registered: 2008-05-12
- Posts: 107
- Website
Difference between Singleton and Static method?
In PHP, for a database class, why should we use Singleton class instead of class with static methods? what are the benefits? e.g. the following code
<?php
class DB1 {
protected static $_db;
public static function query($sql) {
return self::_connect()->mysql_query($sql);
}
protected static function _connect() {
if (!isset(self::$_db))
self::$_db = mysql_connect(/*... params ...*/);
return self::$_db;
}
}
class DB2 {
protected static $_instance;
protected $_db;
protected function __construct() {
}
public static function getInstance() {
if (!isset(self::$_instance))
self::$_instance = new DB2();
return self::$_instance;
}
public function query($sql) {
return $this->_connect()->mysql_query($sql);
}
protected function _connect() {
if (!isset($this->_db))
$this->_db = mysql_connect(/*... params ...*/);
return $this->_db;
}
}
// use static
DB1::query('SELECT * FROM user');
// use singleton
DB2::getInstance()->query('SELECT * FROM user');
?>Today is the tomorrow you worried about yesterday, and all is well. ![]()
FluxBB in Chinese.
Offline
#2 2010-01-04 15:07:46
- Smartys
- Former Developer
- Registered: 2008-04-27
- Posts: 3,117
- Website
Re: Difference between Singleton and Static method?
http://en.wikipedia.org/wiki/Singleton_pattern
Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.
Offline
#3 2010-01-05 02:59:37
- frozen_space
- Member

- From: Wuxi, China
- Registered: 2008-05-12
- Posts: 107
- Website
Re: Difference between Singleton and Static method?
Thanks! Smarty
Today is the tomorrow you worried about yesterday, and all is well. ![]()
FluxBB in Chinese.
Offline
#4 2010-01-05 08:31:07
- artoodetoo
- Member

- From: Far-Far-Away
- Registered: 2008-05-11
- Posts: 206
Re: Difference between Singleton and Static method?
Great topic! I widelly use fully static classes in PHP.
First of all, it is kind of singleton.
Second, I use them as "namespaces" until PHP 5.3|6. It helps me to remove annoing global clause from legacy code.
Last and important for me, static classes (with a class autoloader) simplifies my code. No lost includes, no unitiated objects.
Do you want to see some fluxbb on classes? I have one in development. ![]()
Last edited by artoodetoo (2010-01-05 08:59:12)
Offline
