父类不能被实例化,不能给覆盖。子类实现单例不能使用self,而是用static,它们都是在类体内调用类的方式,区别在于self关键字是在编译时决定它所指代的类,它写在了哪个类中,它指代的就是那个类。而static关键字则是在执行的过程中才决定它所指代的类。
abstract class father{
final protected function __construct(){
$this->init();
}
final protected function __clone(){}
protected function init(){}
//abstract protected function init();
public static function getInstance(){
if(static::$instance === null){
static::$instance = new static();
}
return static::$instance;
}
}
子类声明$instance静态属性,它们从属于各个子类,在父类的getIntance方法中,通过static关键字,调用子类并实例化,然后又赋给子类静态属性$instance。这样就可以实现将获取单例的函数封装在父类的目的。修改子类代码如下:
class Son1 extends Father{
protected static $instance = null;
...
}
class Son2 extends father{
protected static $instance = null;
....
}