Php example of using reflection to insert an object _ PHP Tutorial

Source: Internet
Author: User
Tags php example
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...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.