我们通常在做一个有数据库后台的网站的时候,都会考虑到程序需要适用于不同的应用环境。和其他编程语言有所不同的是,在php中,操作数据库的是一系列的具体功能函数(如果你不使用odbc接口的话)。这样做虽然效率很高,但是封装却不够。如果有一个统一的数据库接口,那么我们就可以不对程序做任何修改而适用于多种数据库,从而使程序的移植性和跨平台能力都大大提高。
php面向对象编程的完成,需要进行对象封装,也就是编写类。我们可以通过生成一个新的sql类实现对数据库的简单封装。例如:
? class sql { var $driver; //实际操作的数据库驱动子类 var $connection; //共用的数据库连接变量 function driverregister($d) { if($d!=) { $include_path = ini_get(include_path); $driverfile = $include_path./.$d..php; //驱动的存放路径必须在php.ini文件中设定的include_path下 if( file_exists( $driverfile)) //查找驱动是否存在 { include($driverfile); $this->driver = new $d(); // 根据驱动名称生成相应的数据库驱动类 return true; } } return false; //注册驱动失败 } function connect($host,$user,$passwd,$database)//连接数据库的函数 { $this->driver->host=$host; $this->driver->user=$user; $this->driver->passwd=$pas swd; $this->driver->database=$d atabase; $this->connection = $this->driver->connect(); } function close()//关闭数据库函数 { $this->driver->close($this->connection); } function query($querystr)//数据库字符串查询函数 { return $this->driver->query($querystr,$this->connection); } function getrows($res)//查找行 { return $this->driver->getrows($res); } function getrowsnum($res)//取得行号 { return $this->driver-> getrowsnum ($res); } } ? >
希望以上介绍的php面向对象编程的相关知识对大家有所帮助。
http://www.bkjia.com/phpjc/446417.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/446417.htmltecharticle我们今天为大家介绍的是关于 下面我们就通过实例来说明使用php面向对象编程的实际意义和应用方法。 我们通常在做一个有数据库后台的...