Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass a Singleton in PHP?

I'm trying to subclass a class that uses singleton pattern and populate the instance with the subclass.

I seem to be having a little trouble.

class Singleton {

    static private $instance;

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

    private function __construct(){}

}

class MySingleton extends Singleton {

}

echo get_class(MySingleton::instance()); //=> Singleton

//=> I'm hoping to see MySingleton
like image 395
maček Avatar asked Nov 02 '11 21:11

maček


2 Answers

What you're looking for is late static binding which is a new feature of PHP 5.3. Try replacing new self() with new static() and this should work for you.

self always references the containing class, whereas static references the "called" class.

like image 177
Michael Mior Avatar answered Sep 28 '22 17:09

Michael Mior


Your singleton base class prevents that as is. if you change the code to this though, it will work.

<?php


class Singleton {

    static private $instances = array();

    static public function instance(){
        $class = get_called_class();
        if(!isset(self::$instances[$class])){
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }

    private function __construct(){}

}

class MySingleton extends Singleton {

}

echo get_class(MySingleton::instance()); //=> MySingleton

Now it works because Singleton allows for one instance per child class.

like image 35
Kris Avatar answered Sep 28 '22 17:09

Kris