PHP面向对象编程快速入门_PHP

WBOY
Release: 2016-06-01 12:25:26
Original
836 people have browsed it

  面向对象编程(OOP)是我们编程的一项基本技能,PHP4对OOP提供了良好的支持。如何使用OOP的思想来进行PHP的高级编程,对于提高PHP编程能力和规划好Web开发构架都是非常有意义的。下面我们就通过实例来说明使用PHP的OOP进行编程的实际意义和应用方法。
  
  我们通常在做一个有数据库后台的网站的时候,都会考虑到程序需要适用于不同的应用环境。和其他编程语言有所不同的是,在PHP中,操作数据库的是一系列的具体功能函数(如果你不使用ODBC接口的话)。这样做虽然效率很高,但是封装却不够。如果有一个统一的数据库接口,那么我们就可以不对程序做任何修改而适用于多种数据库,从而使程序的移植性和跨平台能力都大大提高。
  
  在PHP中要完成OOP,需要进行对象封装,也就是编写类。我们可以通过生成一个新的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);
  }
  }
  ? >
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!