Last Updated: June 11, 2021
·
2.257K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside