Search code examples
phpconstructorsingleton

Singleton in constructor


why it's not work? I want create singleton for connect to db, autoloader, router.

static $singleton = null;

public function __construct(){
    if(empty(self::$singleton)){
        self::$singleton = new self;
        return self::$singleton;
    }
    return self::$singleton;
}

Solution

  • In php method __construct always return instance of class, you can't manipulate the returned value.

    To do what you meant to do, you should use private __conctruct() and create next method for example public static getInstance() with your code:

    static $singleton = null;
    
    public function getInstance(){
        if(empty(self::$singleton)){
            $class = get_called_class();
            self::$singleton = new $class;
        }
        return self::$singleton;
    }