Create a class to connect to the database. let's take a look. Code 1: mysql. class. php & lt ;? Php & nbsp; classSqlTool {& nbsp; private $ conn; & nbsp; private $ host & quot; 127.0.0.1 & quot; & nbsp; private $ user & quot; root & quot; & nbsp; pr creation class method to connect to the database. let's take a look.
Code 1 mysql. class. php
Class SqlTool {
Private $ conn;
Private $ host = "127.0.0.1 ";
Private $ user = "root ";
Private $ password = "5200 ";
Private $ db = "test ";
Function SqlTool (){
$ This-> conn = mysql_connect ($ this-> host, $ this-> user, $ this-> password );
If (! $ This-> conn ){
Die ("failed to connect to database". mysql_error ());
}
Mysql_select_db ($ this-> db, $ this-> conn );
Mysql_query ("set names utf8 ");
}
// Complete select
Function execute_dql ($ SQL ){
$ Res = mysql_query ($ SQL );
Return $ res;
}
// Complete update
Function execute_dml ($ SQL ){
$ B = mysql_query ($ SQL, $ this-> conn );
If (! $ B ){
Return 0; // failed
} Else {
If (mysql_affected_rows ($ this-> conn)> 0 ){
Return 1; // indicates Chen Gong
} Else {
Return 2; // The number of rows is not affected.
}
}
}
}
?>
Code 2 mysql. php
Header ("content-type: text/html; charset = utf-8 ");
Require_once "SqlTool. class. php ";
$ SQL = "select * from user1 ";
$ SqlTool = new SqlTool ();
//
How can I create an object without calling fuction SqlTooL to connect to the database?
$ Res = $ sqlTool-> execute_dql ($ SQL );//
Can I directly call execute_dql to operate the database?
While ($ row = mysql_fetch_row ($ res )){
Foreach ($ row as $ key => $ val ){
Echo "-- $ val ";
}
Echo"
";
}
?> In code 2, I found a problem and created an object. but how can I create an object without calling fuction SqlTooL to connect to the database?
------ Solution --------------------
The SqlTool method of the SqlTool class is its constructor.
From the instruction in the manual:
To achieve backward compatibility, if PHP 5 cannot find the _ construct () function in the class, it will try to find the old constructor, that is, the function with the same name as the class.
We can see that this class is not a waste of time.
Http://php.net/manual/zh/language.oop5.decon.php