This article mainly introduces the example of using reflection to insert objects in php. For more information, see
The Code is as follows:
/**
* Insert insertModel (), which is less efficient by reflection.
* @ Param class $ model object
* @ Param bool $ is_returnLastInsertId whether to return the Add ID
* @ Return int: whether the return value is successful by default. If $ is_returnLastInsertId is true, the return value is "add ID ".
*/
Public function insertModel ($ model, $ is_returnLastInsertId = FALSE ){
Try {
Require_once dirname (_ FILE _). '\ Models \ BaseModel. php ';
If (! Is_subclass_of ($ model, "BaseModel ")){
Exit ($ this-> getError (_ FUNCTION __, _ LINE __));
}
$ ClassName = get_class ($ model );
$ TName = $ this-> formatTabName ($ className );
$ ReflectionClass = new ReflectionClass ($ className );
$ Properties = $ reflectionClass-> getProperties ();
Unset ($ properties [0]);
$ Fields = "";
$ Vals = "";
Foreach ($ properties as $ property ){
$ PName = $ property-> getName ();
$ Fields. = $ pName .",";
$ Vals. = '\ ''. $ model-> $ pName .'\''.',';
}
$ Fields = rtrim ($ fields ,',');
$ Vals = rtrim ($ vals ,',');
$ This-> SQL = "insert into {$ tName} ({$ fields}) values ({$ vals })";
If ($ is_returnLastInsertId ){
$ This-> conn-> exec ($ this-> SQL );
$ LastId = (int) $ this-> conn-> lastInsertId ();
Return $ lastId;
} Else {
$ Row = $ this-> conn-> exec ($ this-> SQL );
Return $ row;
}
} Catch (Exception $ exc ){
Echo $ exc-> getMessage ();
}
}