Search code examples
phpsingletonspl

php singleton keeps calling itself twice in an autoloader class


I made an autoloader class that works as intended, but i have noticed an odd behavior. When I echo out the results of the classes found that are passed to the method that handles the spl_autoload_register() function. I am seeing that I have doubles. Like if the script is called twice, and because its a singleton the data builds 2 arrays in my case.

I am using this method to create my singleton

public static function init()
{
    if (!isset(self::$instance))
        self::$instance = new self();

    return self::$instance;
}

I then have the constructor set to private. I have gone thru each method debugging trying to see where it appears to create a clone of itself.

I suspect that my classes and class for that matter is being cloned somewhere in the spl_autoload_register() function.

any help would be appreciated.


Solution

  • Let the constructor print out something. Just to see if it is really being called more than once. You are using two autloaders right? i would set up sp_autoload_register at the very start of the application (maybe the index.php) and register all required autoloaders. But test if the contructor is being called more than once first.

    // first i would change this:

    private static $instance = null;
    

    // the init function

    public static function init() {
       if (self::$instance === null) {
         self::$instance = new Autoload();
       }
    
       return self::$instance;
    }