上代码:
<?php //自己创建一个数据库Db类 class Db { private $db_host;//主机名 private $db_user;//主机账号 private $db_password;//主机密码 private $db_name;//选择数据库 private $db_char;//选择字符集 private $link;//创建链接对象 public function __construct($db_host2,$db_user2,$db_password2,$db_name2,$db_char2) { $this->db_host = $db_host2; $this->db_user = $db_user2; $this->db_password = $db_password2; $this->db_name = $db_name2; $this->db_char = $db_char2; $this->connect(); $this->char(); } public function connect()//链接数据库方法 { $link2 = mysqli_connect($this->db_host,$this->db_user,$this->db_password,$this->db_name); $this->link = $link2;//$link赋值成为类的属性,就可以用了 if(!$this->link) { echo '链接错误'.mysqli_connect_error(); } } public function char()//设置字符集 { mysqli_set_charset($this->link,$this->db_char); } public function __destruct()//析构方法 { mysqli_close($this->link);//关闭链接 } } $obj = new Db('127.0.0.1','root','root','test','utf8'); var_dump($obj);//输出看看
真的不敢想像,居然自己能做出一个牛逼的类来,加油!,千万别低估自己!!