From the course: PHP: Design Patterns

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Exploring a use case for the singleton pattern

Exploring a use case for the singleton pattern - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

Exploring a use case for the singleton pattern

- Most likely in your code, there's a limited resource, like database connections that are getting created, used and destroyed all over the place. Your code might look something like this, object, object2, object3. Each creating their own connection. The connection class itself just creates a new version of itself every time it's run. When we execute this code, you can see that the constructor is called each and every time. So after calling this class three times, we end up with three instances of the object. This is what it looks like in the browser. Each call created a new object. Now, before we dive into the after example, let me remind you that a singleton is not the same as a global variable. In fact, many people consider this an anti-pattern, which is a poor way of doing things. If you run into a scenario where you think you might need a singleton, check to see if dependency injection makes more sense. Odds are, it will. I'd cover singletons here because you often see them in…

Contents