note 82353 deleted from language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:41:39 +0000 |
| Subject: | note 82353 deleted from language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176107@lists.php.net to get a copy of this message | ||
Note Submitter: Chris N.
----
I have read much of the debate between the singleton pattern and global variables. I think there
are two advantage the singleton has over a global variable.
1.) The singleton can provide protection of the data it holds. The singleton class can define
methods that will proper validate and store data.
2.) A singleton it more maintainable in two ways. Changing the underlying data structure, say a
string to an array, will take much less effort using a singleton than using a global variable where
you would have to find every time the global variable is modified (which can be mitigated with
regular expressions). Second, the global variable can be changed and modified at any point in your
code base which can cause problems with debugging large code bases, or code that relies on different
libraries.
A practical example would be a way to log messages in an application.
With a global variable you can do:
<?PHP
$g_log = '';
// or
$g_log = array();
// But at any point $log can be wiped out or changed. i.e.
$g_log = 42;
// Where as a singleton can't in inadvertently lose data.
class Log {
public static function instance() {
static $_instance = null;
if (is_null($_instance)) {
$_instance = new Log();
}
return $_instance;
}
public function logMsg($s) {
// Validate
// Now add
}
}
$s_log = Log::instance();
// So if happens somewhere, unexpectedly
$s_log = 42;
// You will still have your log in the Log class and
$s_log->log("Hello World!");
/* Where as if $g_log was originally a string and you
wanted to change it to a global you would have to change */
$g_log .= 'Hello World!';
// to
$g_log[] 'Hello World!';
?>
If you change the underlying way in which the Log class stores the messages the above statement will
not have to be changed.
If you want the speed or don't care about the security then use a singleton. If you want the
security or maintainability then use a singleton.
Finally, the best thing you can do is use a consistent coding style throughout your code no matter
what approach you take.