Detailed explanation of PHP singleton design pattern to connect to database

小云云
Release: 2023-03-22 15:58:01
Original
1539 people have browsed it

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`");
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template