耪失险苍溅怕叛持巴纤渭来蓝
作用域: 静态成员属于类所有,必须用类进行调用,不能使用对象调用
计算机内存示意图
新建Db类和demo4.php
Db.php:
<?php //使用静态成员,定义数据库操作类 /** * 类中的静态成员:静态属性与静态方法 * 作用域: 静态成员属于类所有,必须用类进行调用,不能使用对象调用 * 该类的静态成员,被该类的所有实例对象所共享 * 静态成员的引用: 在类中使用 self::, 在类外部使用 类名:: * 类成员静态化,是面向对象编程的一种趋势,有很多的模拟手段,请格外重视 * 类成中静态化使用关键字:static来实现 * 静态技术的另一个使用场景是: 静态延迟绑定技术,后面我们会详细学习 */ class Db { public static $dbtype="MySQL"; protected static $db=null;//数据库连接对象 //含有默认值的参数写在后面,避免出错 public function __construct($user,$password,$database,$host='127.0.0.1',$port=3306) { //self:当前类 //对当前类的静态成员进行初始化 self::$db=mysqli_connect($host,$user,$password,$database,$port); if(mysqli_connect_error(self::$db)) { exit('连接失败'.mysqli_connect_error(self::$db)); } } //数据库的连接查询,获取数据库连接对象$db //注意:必须是静态函数 public static function getDb() { //如果初始化成功则返回mysqli连接对象,否则返回null // return self::$db ? self::$db : null; // 简写: return self::$db ? : null; } }
demo4.php
<?php /** * 数据库的静态操作 */ require "./class/Db.php"; $db=new Db('root','root','myuser'); var_dump(Db::getDb());
执行:
查询用户信息:
Db.php
<?php //使用静态成员,定义数据库操作类 class Db { public static $dbtype="MySQL"; protected static $db=null;//数据库连接对象 //含有默认值的参数写在后面,避免出错 public function __construct($user,$password,$database,$host='127.0.0.1',$port=3306) { //self:当前类 //对当前类的静态成员进行初始化 self::$db=mysqli_connect($host,$user,$password,$database,$port); if(mysqli_connect_error(self::$db)) { exit('连接失败'.mysqli_connect_error(self::$db)); } } //数据库的连接查询,获取数据库连接对象$db //注意:必须是静态函数 public static function getDb() { //如果初始化成功则返回mysqli连接对象,否则返回null // return self::$db ? self::$db : null; // 简写: return self::$db ? : null; } //查询数据 public static function select($table,$fields=" * ",$where="",$order="") { //sql语句 $sql="select {$fields} from {$table} {$where} {$order}"; //执行sql语句 $res=mysqli_query(self::$db,$sql); //获取结果集 while($row=mysqli_fetch_assoc($res)) { $rows[]=$row;//将结果存入二维数组中 } return $rows;//二维数组,从当前表中查询到的数据 } }
demo4.php
<?php /** * 数据库的静态操作 */ require "./class/Db.php"; $db=new Db('root','root','myuser'); $table="staff"; $fields="name,age"; $where="where age < 25"; $order="order by age desc"; //静态成员属于类所有,必须用类进行调用,不能使用对象调用 //调用方式 类:: echo "<pre>".print_r(Db::select($table,$fields,$where,$order),true)."</pre>";
执行:
还可以做增删改查的操作,封装完成类似thinkphp的Db类
副诵帮省宫钎小济蠕毖价剑寥