Object-oriented Programming (OOP) is a basic skill in our programming, and PHP4 provides good support for OOP. How to use OOP idea to do advanced PHP programming is very meaningful for improving PHP programming ability and planning web development architecture. Here we illustrate the practical meaning and application of programming using PHP's OOP by examples.
We usually do a Web site with a database background, we will take into account the application needs to apply to different environments. Unlike other programming languages, in PHP, the operation of a database is a series of specific functional functions (if you do not use an ODBC interface). This is highly efficient, but not enough to encapsulate. If there is a unified database interface, then we can not make any changes to the program to apply to a variety of databases, so that the porting of the program and cross-platform capabilities are greatly improved.
To complete oop in PHP, you need to encapsulate the object, which is to write the class. We can implement a simple encapsulation of the database by generating a new SQL class. For example:
?
Class SQL
{
var $Driver; Database-driven subclass of the actual operation
var $connection; Shared Database connection variables
function Driverregister ($d)
{
if ($d!= "")
{
$include _path = Ini_get ("include_path");
$DriverFile = $include _path. " /". $d.". PHP ";
The drive store path must be under Include_path set in the php.ini file
if (file_exists ($DriverFile))//Find driver exists
{
Include ($DriverFile);
$this->driver = new $d ();
Generate a corresponding database-driven class based on the driver name
return true;
}
}
return false; Registration driver failure
}
Function Connect ($host, $user, $passwd, $database)//functions connected to the 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 ()//Closing database functions
{
$this->driver->close ($this->connection);
}
function query ($QUERYSTR)//database string query functions
{
return $this->driver->query ($queryStr, $this->connection);
}
function GetRows ($res)/lookup row
{
return $this->driver->getrows ($res);
}
function Getrowsnum ($res)//Get line number
{
return $this->driver-> getrowsnum ($res);
}
}
?>