摘要:<?php // 创建数据库的单利模式 2019-04-20 class Connsql { // 把 构造函数,克隆函数 私有化 private function __construct()
<?php // 创建数据库的单利模式 2019-04-20 class Connsql { // 把 构造函数,克隆函数 私有化 private function __construct(){} private function __clone(){} // 添加受保护的私有属性 protected static $Link = null; // 创建静态方法 public static function Linksql($type,$host,$dbname,$user,$pwd) { // 静态属性是否为空null,为空则创建数据库对象 if(is_null(static::$Link)) { $dsn = "{$type}:host={$host};dbname={$dbname}"; static::$Link = new PDO($dsn,$user,$pwd); } return static::$Link; } } // 创建pdo 对象 $pdo = Connsql::Linksql('mysql','127.0.0.1','php_edu','root','root'); // 查询SQL $sql = "SELECT * FROM `users`"; // sql预处理 $stmt = $pdo->prepare($sql); // 执行预处理 if($stmt->execute()) { //获取结果集 $res = $stmt->fetchall(); echo '<pre>'; print_r($res); } else { // 输出错误 print_r($stmt->errorInfo()); }
批改老师:天蓬老师批改时间:2019-04-22 09:40:48
老师总结:如果一个类, 仅允许实例化一次, 那么就要从系统收回类实例化的权限, 交给用户决定 .... , 由用户决定 什么时候实例化, 以及如何进行....