Php example of inserting objects using reflection. This article mainly introduces the example of using reflection to insert objects in php. For more information, see the following code: *** insert insertModel () and use reflection, slightly less efficient * @ paramclass $ mod 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 () and use reflection, slightly less efficient * @ param class $ model object * @ param bool $ is_returnLastInsertId whether to return adding ID * @ return int whether to return success by default, $ is_returnLastInsertId is true, returns the 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 ();}}
The callback code is as follows:/*** insert insertModel (), and use reflection to slightly reduce the efficiency * @ param class $ mod...