Hello there!
I've managed to inherit some code for a small plugin for tiny_mce. In cleaning it up, I added a logging feature and I discovered that a particular php object was created multiple times from different scripts. There was no need for a new instance of the object each time, and I thought a singleton design pattern may be more appropriate.
So I changed the class to use a singleton design pattern (I used a static in-class singleton pattern rather than an external helper method like the one at: http://www.ibm.com/developerworks/libra ... signptrns/), but kept the log messages to know when new was being called and which script created it. I ensured that the constructor was private, and that calling classes used the pattern.
I ran the program and ensured it ran as expected.
Then I checked the logs, I *expected* that there would be one call where the object would be created, and everything else would get the information from the static variable.
Instead, based on the logs, the scripts are STILL creating this object everywhere.
So my question is: When SHOULD a new singleton get created? What is its scope?
Singleton question
Moderator: General Moderators
- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
Re: Singleton question
The singleton design pattern does not support the use of the "new" keyword. I suspect that you are using it though, if you are creating the object.
Re: Singleton question
Surely if your constructor is private "new" wouldn't work though...
Re: Singleton question
Show your code.
What you are refer "a static in-class singleton pattern" and "external helper method" to?
What you are refer "a static in-class singleton pattern" and "external helper method" to?
Re: Singleton question
PHP does not have singletons, you have to emulate it. Private constructors will enforce usage of your static factory method
Re: Singleton question
private constructors raise recoverable errors, not fatal ones, so ensure error logging is enabled.
Re: Singleton question
I thought private caused a fatal error. Protected causes recoverable.