Php Singleton Trait and using it in a Class

Singleton is an OOP concept which is used to support instantiating class only once. So basically it just uses already created instance of the class which is stored in a static variable.

Traits are one of the ways of inheritance in PHP for more detail check Traits.

Code Snippet:

This is how you can create a Trait and use it in a class.

Some points to keep in a note. In Trait, the constructor is protected so one can’t create an instance of the class by just calling new SingletonClass(). It will give a fatal error.

PHP Fatal error:  Uncaught Error: Call to protected SingletonClass::__construct() from invalid context
Written on March 30, 2019