可以在PHP中定义接口单例吗?
我想定义一个单例基类型,用户将从中派生他的类,所以我的想法是:可以在PHP中定义接口单例吗?,php,oop,singleton,Php,Oop,Singleton,我想定义一个单例基类型,用户将从中派生他的类,所以我的想法是: interface SingletonInterface { public static function getInstance(); } abstract class SingletonAbstract implements SingletonInterface { abstract protected function __construct(); final private function __
interface SingletonInterface {
public static function getInstance();
}
abstract class SingletonAbstract implements SingletonInterface {
abstract protected function __construct();
final private function __clone() {}
}
但是使用这个方法,用户可以实现这个单例
class BadImpl implements SingletonInterface {
public static function getInstance() {
return new self;
}
}
您的建议是什么?我使用以下代码创建一个单例:
abstract class Singleton {
private static $_aInstance = array();
private function __construct() {}
public static function getInstance() {
$sClassName = get_called_class();
if( !isset( self::$_aInstance[ $sClassName ] ) ) {
self::$_aInstance[ $sClassName ] = new $sClassName();
}
$oInstance = self::$_aInstance[ $sClassName ];
return $oInstance;
}
final private function __clone() {}
}
这是在使用此模式:
class Example extends Singleton {
...
}
$oExample1 = Example::getInstance();
$oExample2 = Example::getInstance();
if(is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2){
echo 'Same';
} else {
echo 'Different';
}
记住PHP不允许多重继承,所以您必须仔细选择类的基础。Singleton很容易实现,最好让每个类定义它。
还要注意,私有字段没有移植到后代类,因此可以有两个同名的不同字段。首先:如果项目中有太多的单例,那么可能会在投影级别上搞砸一些事情 第二:Singleton应该在那里使用,而且只有在那里,一个类的多个实例完全没有意义或者可能导致一些错误
最后:继承并不是为了减少代码量而设计的你现在可以使用traits了,但是你需要这么多的单例吗?(相关)我曾想过这种方法,但它有一些缺点。。1.PHP5.3是必需的。类充当SingletonContainer 3。派生类被认为是不同的4。您正在调用构造函数,但它的优点是您只需要扩展该类就可以拥有一个单例