<? php
require_once ' DB.php ' ;
class DatabaseConnection{
public static function get(){
static $db = null ;
if ( $db === null ){
$db = new DatabaseConnection();
}
return $db ;
}
private $_handle = null ;
# 构造方法是私有的,所以不能字节使用 new 关键字实例化,这点对于单件模式至关重要
private function __construct(){
$dsn = ' mysql://root:root@localhost/test ' ;
$this -> _handle = DB :: connect( $dsn , array ());
}
public function handle(){
return $this -> _handle;
}
}
print ( " Handle = " . DatabaseConnection :: get() -> handle() . " " );
print ( " Handle = " . DatabaseConnection :: get() -> handle() . " " );
print_r ( get_included_files ());
# 下面是单件模式的原型,注意三个要点,
# 1. 对象必须是私有成员.
# 2.私有的构造函数
# 3. 一个公共的实例化并返回该Singleton的可被外部对象调用的成员函数
# 单件模式的事例化过程被从外部移到了内部.只有通过内部方法才能实例化对象
class Singleton{
private static $instance = null ;
private function __construct(){
}
public static function getInstance(){
if (self :: $instance === null ){
self :: $instance = new Singleton();
}
return self :: instance;
}
}
?>