-4

what is the design pattern for this code ?

class Foo {
    private $_connection;
    private static $_instance;
    private $_host = "Host";
    private $_username = "Name";
    private $_password = "encrypted Word";
    private $_database = "Name";

    public static function getInstance() {
        if(self::$_instance = 'Connected') {
            self::$_instance = new self();
        } 

        return self::$_instance;
    }

    private function __construct() {
        $this->_connection = new mysqli($this->_host, $this->_username,
            $this->_password, $this->_database);
    }

    public function getConnection() {
        return $this->_connection;
    }

}
Philipp
  • 15,377
  • 4
  • 35
  • 52
Hamza
  • 469
  • 3
  • 9

1 Answers1

1

This should maybe be a singleton, but currently is has bugs and won't work as expected.

The aim of a singleton is, to only have one instance of a class and no possibility to create another one. To achieve this, one creates a static method (getInstance), which stores the instance of the class and lazy instantiates it.

Currently there is a bug

if (self::$instance = 'Contected') ...

First, this isn't a comparison and because of this, the value is always true and each time you call getInstance, you actually create a new one, instead of returning the singleton.

This should be changed to

if (!self::$instance) ...

To get the actual singleton, you simply have to call the getInstance-method.

$foo = Foo::getInstance();
Philipp
  • 15,377
  • 4
  • 35
  • 52