Reputation: 6852
I know how to create a singleton class in php. But i am confused that if we can able to clone that then it is waste of that class.
May i know how to restrict the singleton class from cloning? please check the code below:
class DatabaseConnection {
private static $singleton_instance = null;
private function construct__() {
// Declaring the constructor as private ensures
// that this object is not created as a new intance
// outside of this class. Therefore you must use the
// global_instance function to create this object.
}
public static function global_instance() {
static $singleton_instance = null;
if($singleton_instance === null) {
$singleton_instance = new DatabaseConnection();
}
return($singleton_instance);
}
}
Upvotes: 4
Views: 1418
Reputation: 1151
Just make your function __clone() private.
private function __clone() { }
It will throw a Fatal Error if you try to access it.
Upvotes: 8
Reputation: 1995
There is a __clone()
method that will help you to prevent cloning.
public function __clone()
{
trigger_error('Cloning forbidden.', E_USER_ERROR);
}
Upvotes: 1