Answer the question
In order to leave comments, you need to log in
What is the difference between the Singleton pattern?
Read the description here:
job-blog.bullgare.ru/2009/07/design-patterns-in-php/
$db = mysqli_connect('localhost','aa','bb','cc');
mysqli_set_charset($db, "utf8");
Answer the question
In order to leave comments, you need to log in
but mysqli_connect is a transitional function created for shitcoders who still haven't switched their site to PDO or for people who can't do it due to the fault of the customer.
$db in this case is not a singleton, since a singleton should provide one entry point and one object, and you have
1. Not an object at all and not even an oop,
1.1 emerges from this. There is no entry point as such, you first create a variable and then use it... as a variable.
1.2. Your variable is not protected from changes and can be overwritten at any time
1.3. To access a variable from anywhere in the code, put it in the global scope, in a singleton this is decided at the class visibility level
If it were a singleton, a tricky function would be sewn inside your variable that creates a connection the first time it is accessed, and later returns it, you could also monitor switching to backup databases and much more. Your connection is always created, in a fixed place, and even if it is unnecessary, it is still created.
And all this is inside the variable itself, which leads us to the fact that this should be done in OOP, since there is simply no such functionality in PHP to track the first access to a variable.
The following code is an example implementation of a Singleton:
class Users
{
private static $instance;
private $params = [];
private function __construct(){}
public static function getInstance()
{
if( empty( self::$instance ) ){
self::$instance = new self();
}
return self::$instance;
}
public function set( $key, $value )
{
$this->params[ $key ] = $value;
return $this;
}
public function get( $key )
{
return isset( $this->params[ $key ] ) ? $this->params[$key] : false;
}
}
$user = Users::getInstance();
$user->set( 'name', 'Dmitriy' );
echo $user->get('name');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question