Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern in php

Tags:

php

singleton

class SingleTon
{
    private static $instance;

    private function __construct()
    {
    }

    public function getInstance() {
        if($instance === null) {
            $instance = new SingleTon();
        }
        return $instance;
    }
}

The above code depicts Singleton pattern from this article. http://www.hiteshagrawal.com/php/singleton-class-in-php-5

I did not understand one thing. I load this class in my project, but how would I ever create an object of Singleton initially. Will I call like this Singelton :: getInstance()

Can anyone show me an Singleton class where database connection is established?

like image 937
theJava Avatar asked Apr 22 '26 23:04

theJava


1 Answers

An example of how you would implement a Singleton pattern for a database class can be seen below:

class Database implements Singleton {
    private static $instance;
    private $pdo;

    private function __construct() {
        $this->pdo = new PDO(
            "mysql:host=localhost;dbname=database",
            "user",
            "password"
        );
    }

    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->pdo;
    }
}

You would make use of the class in the following manner:

$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before

And for reference, the Singleton interface would look like:

interface Singleton {
    public static function getInstance();
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!