Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict a singleton class from cloning?

Tags:

php

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);
}
}
like image 494
Vinoth Babu Avatar asked Oct 23 '25 08:10

Vinoth Babu


2 Answers

Just make your function __clone() private.

private function __clone() { }

It will throw a Fatal Error if you try to access it.

like image 149
Debflav Avatar answered Oct 24 '25 21:10

Debflav


There is a __clone() method that will help you to prevent cloning.

public function __clone()
{
    trigger_error('Cloning forbidden.', E_USER_ERROR);
}
like image 20
Kevin Labécot Avatar answered Oct 24 '25 23:10

Kevin Labécot



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!