Last Updated: June 11, 2021
·
2.008K
· chris15001900

php singleton

Singleton allows you to create an object that has only one instance, e.g. database class to avoid multiple connections:

class Database {

    private static $instance = false;   

    private function __construct() {
            $this->connect();           
    }

    public static function getInstance() {

            if(self::$instance == false) {

                    self::$instance = new Database();

            }

            return self::$instance;                 

    }

    public function connect() {
        // create connection
    }

Then, instead of creating an object, you call a static method of Database class:

$db = Database::getInstance();

Notice the private constructor and $instance variable inside a class.