Send by LINE
B! Bookmarks in Hate-bu
Bookmarks in Pocket
RSS feeds

php: How to easily create a singleton class

Other language site
No available translations found
Google Translate
php logo

I created a trait to easily make singletons of php classes. Just by implementing this with use it will be a singleton class.

What is singleton?

Singleton is a technique to restrict the creation of only one instance of a class.
Specifically, disable the instance creation (new operator) of the class.

Singleton is used to restrict instance creation, for the purpose of suppressing memory consumption, for holding common data in a program, etc.

I created a trait to make that class singleton class. Let's see the sample.

How to create a singleton class

namespace Test;

trait Singleton {
    private static $instance;

    protected function __construct() {

    public static function get_instance() {
        if ( empty( self::$instance ) ) {
            self::$instance = new self();
        return self::$instance;

$Instance in line 5 is the only property that holds an instance of a singleton class that implements trait. Since it is the only one to hold, add a static.

By making it protected in line 7, I can not create instance of singleton class. With this you can not use the new operator in the singleton class.
I use protected here, but it can be private.

Because new operator can not be used from outside, get_instance() should be a static method.

The only instance that can be referenced is when you call the get_instance() method. Returns the instance of the singleton class that is held only by this function.

We will use this trait in the class to make it a singleton class. The way to make a class a singleton class is as follows.

namespace Test\Classes

use Test\Singleton

class Sample {
    use Singleton;


The usage of trait is detailed in the official document of php.



Get instance of singleton class by setting Sample::get_instance().

You can easily create as many singleton classes as you can by placing the singleton function in a trait.


If you implement the singleton feature in super class, you may think that it is not a trait.
But in super class it is not possible to implement singleton functionality. "new self" is an instance of a super class and not an instance of a child class.

Also, child classes that inherit the singleton class that implements the trait created this time will not become a singleton. The reason is the same.

Leave a Reply