- UID
- 1
- 贡献
- 844
- 金币
- 1540
- 主题
- 520
- 在线时间
- 333 小时
- 注册时间
- 2022-1-15
- 最后登录
- 2024-11-12
|
发表于 2022-12-10 21:05:04
| 355 |
0 |
显示全部楼层
|阅读模式
php教程单例、初始化参数、实例化PDO
语法代码如下:
- <?php
- class MyPDO{
- private $type; //数据库类别
- private $host; //主机地址
- private $port; //端口号
- private $dbname; //数据库名
- private $charset; //字符集
- private $user; //用户名
- private $pwd; //密码
- private $pdo; //保存PDO对象
- private static $instance;
- private function __construct($param) {
- $this->initParam($param);
- $this->initPDO();
- }
- private function __clone() {
- }
- public static function getInstance($param=array()){
- if(!self::$instance instanceof self)
- self::$instance=new self($param);
- return self::$instance;
- }
- //初始化参数
- private function initParam($param){
- $this->type=$param['type']??'mysql';
- $this->host=$param['host']??'127.0.0.1';
- $this->port=$param['port']??'3306';
- $this->dbname=$param['dbname']??'data';
- $this->charset=$param['charset']??'utf8';
- $this->user=$param['user']??'root';
- $this->pwd=$param['pwd']??'root';
- }
- //初始化PDO
- private function initPDO(){
- try{
- $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";
- $this->pdo=new PDO($dsn, $this->user, $this->pwd);
- } catch (PDOException $ex) {
- echo '错误编号:'.$ex->getCode(),'<br>';
- echo '错误行号:'.$ex->getLine(),'<br>';
- echo '错误文件:'.$ex->getFile(),'<br>';
- echo '错误信息:'.$ex->getMessage(),'<br>';
- exit;
- }
- }
- }
- //测试
- $param=array(
- );
- $mypdo= MyPDO::getInstance($param);
- var_dump($mypdo);
复制代码
|
|