PHP 设计模式之单例模式

  1. <?php
  2. header("Content-Type:text/html;charset=utf-8");
  3. /**
  4. *单例模式实现 数据库操作类
  5. *实例化一次,赋值给静态变量,当再次调用类中方法,只需判断这个变量是否有值即可,无需再实例化类一次
  6. **/
  7. class db
  8. {
  9. public $conn;
  10. public static $sql;
  11. public static $instance=null;
  12. //构造方法和clone 方法设置为私有属性,防止外部访问
  13. private function __construct()
  14. {
  15. require_once "dbConfig.php";
  16. $this->conn=mysql_connect($db['host'],$db['user'],$db['password']);
  17. if (!mysql_select_db($db['database']))
  18. {
  19. echo '连接数据库失败';
  20. }
  21. mysql_query('set names utf8');
  22. }
  23. //private function __clone() {}; //覆盖克隆方法,禁止克隆
  24. //构造单实例方法
  25. public static function getInstance()
  26. {
  27. if (!(self::$instance instanceof self))
  28. {
  29. self::$instance=new db;
  30. }
  31. return self::$instance;
  32. }
  33. /*
  34. *数据库查询方法
  35. *@$table 表名
  36. *@$data 需要查询的条件数据
  37. *@$field 需要查询的字段
  38. */
  39. public function select($table,$data,$field=null)
  40. {
  41. $where='where 1=1';
  42. if (!empty($data))
  43. {
  44. foreach ($data as $key=>$val)
  45. {
  46. $where.=' and '.$key.'='."'$val'";
  47. }
  48. }
  49. $fieldstr='';
  50. if (!empty($field))
  51. {
  52. foreach ($field as $k=>$v)
  53. {
  54. $fieldstr.=$v.',';
  55. }
  56. $fieldstr=rtrim($fieldstr,',');
  57. }else
  58. {
  59. $fieldstr='*';
  60. }
  61. /**
  62. *构造sql语句
  63. *
  64. **/
  65. self::$sql="select {$fieldstr} from {$table} {$where}";
  66. $res=mysql_query(self::$sql,$this->conn);
  67. $i=0;
  68. $result=array();
  69. while($row=mysql_fetch_assoc($res))
  70. {
  71. foreach ($row as $key=>$val)
  72. {
  73. $result[$i][$key]=$val;
  74. }
  75. $i++;
  76. }
  77. return $result;
  78. }
  79. /**
  80. * insert update方法
  81. **/
  82. //public function insert(){};
  83. //public function update(){};
  84. }
  85. /**
  86. *
  87. *外部调用
  88. *
  89. **/
  90. $db=db::getInstance();
  91. $arr=$db->select('user',array('username'=>'luowj'),array('username','password'));
  92. var_dump($arr);
  93. ?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值