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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With