← back to the blog


Singleton class in PhP? The 'why' and 'how'.

Posted on October 2nd, 2018 in PhP by George

 

PHP Singleton, the structure and practical example. Useful in order to restrict the number of instances. Estabilishing a connection with a database it is time consuming. Here Singleton can help by providing the same open connection when required instead of instantiating a new one.

By declaring an private constructor you automaticaly prevent creation of objects outside the class.

 
<?php
class Singleton {
private static $instance = null;
// constructor is private no outer
// code cand initiate objects
private function construct()
{
}
public static function getInstance()
{
if (self::$instance == null){
self::$instance = new Singleton();
}
return self::$instance;
}
}
$test1 = Singleton::getInstance();
$test2 = Singleton::getInstance();
var_dump($test1,$test2);
?>
 

 

 Let's use singleton pattern to establish a database connection.

<?php

class DbConnection
{
private static $instance = null;
private $connection = null;

// private variables for db connection

private $host = '127.0.0.1';
private $user = 'username';
private $pass = 'password';
private $name = 'db name';
private $charset = 'utf8mb4';

//here we make sure is not posible to use constructor
// to create objects outside of this class declaration

private function __construct(){
$this->connection = 'database connection logic';
}

//logic for initiating the first instance

public static function getInstance(){

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

	self::$instance = new DbConnection();

	}

return self::$instance;

	}
	public function connect()
	{
	return $this->connection;
	}
}

$instance = DbConnection::getInstance();

$conn = $instance→connect()

var_dump($instance);

$instance = DbConnection::getInstance();

$conn = $instance→connect();

var_dump($instance);

?>