What we will introduce to you today is aboutNext we will illustrate the practical significance and application methods of using PHP object-oriented programming through examples.
When we create a website with a database background, we usually consider that the program needs to be applicable to different application environments. Different from other programming languages, in PHP, database operations are a series of specific functions (if you do not use ODBC interfaces ). Although this method is highly efficient, it is not encapsulated. If there is a unified database interface, we can apply to multiple databases without making any modifications to the program, so that the program portability and cross-platform capabilities are greatly improved.
The completion of PHP object-oriented programming requires object encapsulation, that is, writing classes. We can implement simple database Encapsulation by generating a new SQL class. For example:
- <?
- Class SQL
- {
- Var $ Driver; // a subclass of the actual database Driver
- Var $ connection; // shared database connection variable
- Function DriverRegister ($ d)
- {
- If ($ d! = "")
- {
- $Include_path=Ini_get("Include_path ");
- $DriverFile= $ Include_path. "/". $ d. ". php ";
- // The path where the driver is stored must be in the INCLUDE_PATH set in the PHP. ini file.
- If (file_exists ($ DriverFile) // you can check whether the driver exists.
- {
- Include ($ DriverFile );
- $ This->Driver=New$ D ();
- // Generate the corresponding database Driver Class Based on the driver name
- Return true;
- }
- }
- Return false; // driver registration failed
- }
- Function Connect ($ host, $ user, $ passwd, $ database) // function used to Connect 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 () // closes the Database function
- {
- $ This->Driver->Close ($ this->Connection );
- }
- Function Query ($ queryStr) // database string Query function
- {
- Return $ this->Driver->Query ($ queryStr, $ this->Connection );
- }
- Function getRows ($ res) // find a row
- {
- Return $ this->Driver->GetRows ($ res );
- }
- Function getRowsNum ($ res) // obtain the row number
- {
- Return $ this->Driver->GetRowsNum ($ res );
- }
- }
- ?>
I hope that the above PHP object-oriented programming knowledge will help you.