Home  >  Article  >  Backend Development  >  Detailed explanation of PHP singleton design pattern to connect to database

Detailed explanation of PHP singleton design pattern to connect to database

小云云
小云云Original
2018-03-29 11:08:451543browse

This article mainly shares with you the detailed explanation of PHP singleton design pattern to connect to the database. It is mainly shared with you in the form of code. I hope it can help you.

<?php
    /**
     *PHP面向对象:单态设计模式(连接数据库)
     */
    class DB{
        private static $obj=null;  // 声明一个私有的数据库对象
        // 数据库连接的一些信息
        private function __construct(){
            echo "连接数据库成功";
        }
        // 返回数据库连接对象(静态方法)
        static function getInstance(){
            if(is_null(self::$obj)){  // 数据库对象不存在时
                self::$obj=new self();  // 实例化
            }
            return self::$obj;  // 返回数据库对象
        }
    }
    $db=DB::getInstance();  // 数据库对象
    $db->query("select * from `student`");

Related recommendations:

Introducing three commonly used design patterns in PHP: singleton design pattern, factory design pattern and observer design pattern.

The above is the detailed content of Detailed explanation of PHP singleton design pattern to connect to database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn