How would one create a Singleton class using PHP5 classes?
This article covers topic quite extensively: http://www.phptherightway.com/pages/Design-Patterns.html#singleton
Note the following:
- The constructor
__construct()
is declared asprotected
to prevent creating a new instance outside of the class via thenew
operator.- The magic method
__clone()
is declared asprivate
to prevent cloning of an instance of the class via theclone
operator.- The magic method
__wakeup()
is declared asprivate
to prevent unserializing of an instance of the class via the global functionunserialize()
.- A new instance is created via late static binding in the static creation method
getInstance()
with the keywordstatic
. This allows the subclassing of theclass Singleton
in the example.