- 构造函数一定要声明为
private
;
-
$_instance
一定要声明为 private
static
;
-
__clone
一定要定义且private
,防止clone;
-
getInstance()
一定要声明为public
static
;
- 抽象类中的抽象方法,子类必须重写
testFunction()
;
abstract class SingletonBase
{
public $table = 'bar';
private static $_instance;
private function __construct()
{
echo 'this is the private parent construct';
}
public static function getInstance($className)
{
if (!self::$_instance instanceof self) {
self::$_instance = new $className();
}
self::$_instance->testFunction();
return self::$_instance;
}
abstract function testFunction();
private function __clone()
{
trigger_error('Clone is not allow!', E_USER_ERROR);
}
}
class SingletonFoo extends SingletonBase
{
public $table = 'foo';
public static function getInstance()
{
return parent::getInstance(__CLASS__);
}
public function testFunction()
{
echo 'test function</p>';
}
}
$st = SingletonFoo::getInstance();