Using Interfaces and Abstract Classes in PHP

In this PhpRiot Snippet I will show you how to create and use singleton classes. A singleton class is a class that can instantiated once only. While it may not come up frequently, it can be a useful technique when it simply doesn’t make sense to have than one instance of a class.

To achieve this we cannot instantiate it directly using the new keyword. Instead, we must use a static class method to access the create and access the instance.

The key steps in creating singleton classes are as follows:

  • Prevent direct instantiation by making the contructor private
  • Store the only instance of the class as a static property of the class.
  • Provide a static method to access the instance. The instance is created the first time this method is called.

Let’s say we want to create a singleton class called MySingleton. The following code defines this class, including the private constructor so it cannot be directly instantiated.

Next we add a static property called $_instance. We make this private so it cannot be accessed except through the static method we’ll also create. The convention for the singleton accessor method is to name is GetInstance (or getInstance, depending on your preference).

The GetInstance method first checks if the $_instance property is a MySingleton. If it’s not, the one and only instance is created. Once it has been created it can be returned.

The following listing shows how you can access and use the object.

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *