This code is commonly used when we encode some frameworks (such as thinkphp).
M (' User ')->where (array (' ID ' =>1))->field (' name ')->select ();
This is not only conducive to coding, but also can make people "happy". Well, don't say much. Let's see how it's achieved.
Database operations base class [PS: implementation of major functional coherence functions]
Class db{
This property defines the name of the method to implement a coherent operation
Public $sql = Array (
"Field" => "",
"Where" => "",
"Order" => "",
"Limit" => "",
"Group" => "",
"Having" => "",
);
/**
* In a coherent operation, call the field () where () order () limit () group () has () method and combine it into an SQL statement
* This method is a PHP magic method that automatically calls this method when a method that does not exist in the class is invoked
* @param a string that receives the name of this method when $methodName call a method that does not exist
* @param $args to call a method that does not exist, receive the parameter of this method and receive it as an array
*/
function __call ($methodName, $args) {
The name of the method to be requested, unified to lowercase
$methodName =strtolower ($methodName);
If the request method name corresponds to the $sql subscript of the member property array, the second argument is assigned to the "subscript corresponding element" in the array.
if (Isset ($this->sql[$methodName])) {
$this->sql[$methodName]= $args [0];
}else{
Echo ' Invoke class '. Get_class ($this). ' In the '. $methodName. ' () method does not exist ';
}
Returns the object so that the method in this object can continue to be invoked to form a coherent operation
return $this;
}
/**
* Use this method to splice into a select SQL statement; [PS: This method ends the coherent operation and is placed on the last side of the coherent operation]
*/
function Select () {
concatenation of SQL strings in the SELECT syntax [PS: Can be executed on the MySQL command line in the Help select; View its syntax knot]
$sql = "Select {$this->sql[' field ']} from test {$this->sql[' where '} {$this->sql[' group ']} {$this->sql[' Has ']} {$this->sql[' order ']} {$this->sql[' limit ']} ';
Echo $sql;
}
}
$obj =new db ();
$obj->field (' name,sex,address ')->where (' Where name= ' Gongwen ')->limit (' Limit 1 ')->select ();
Output: SELECT name,sex,address from Test where Name=gongwen limit 1