Home > Article > Backend Development > Detailed explanation of PHP singleton design pattern to connect to database
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:
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!