1. <?php
    2. //三私一公
    3. class DB {
    4. //静态的属性用来保存对象的单例
    5. private static $instance;
    6. //私有的构造方法阻止在类的外部实例化
    7. private function __construct() {
    8. }
    9. //私有的__clone()阻止在类的外部clone对象
    10. private function __clone() {
    11. }
    12. public static function getInstance() {
    13. //保存的值不属于DB类的类型就实例化
    14. if(!self::$instance instanceof self)
    15. self::$instance=new self();
    16. return self::$instance;
    17. }
    18. }
    19. //测试
    20. $db1=DB::getInstance();
    21. $db2=DB::getInstance();
    22. var_dump($db1,$db2); //object(DB)#1 (0) { } object(DB)#1 (0) { }