Home >Backend Development >PHP Tutorial >Example of inserting objects using reflection in php_PHP tutorial

Example of inserting objects using reflection in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:36:07670browse

This article mainly introduces examples of using reflection to insert objects in PHP. Friends in need can refer to it

The code is as follows: /**​ * InsertModel(), using reflection, slightly less efficient * @param class $model object * @param bool $is_returnLastInsertId whether to return the added ID * @return int Default returns success or failure, $is_returnLastInsertId is true, returns the added ID ​*/ Public function insertModel($model,$is_returnLastInsertId=FALSE) { try {                 require_once dirname(dirname(__FILE__)).'ModelsBaseModel.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(); } } }

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/740411.htmlTechArticleThis article mainly introduces examples of using reflection to insert objects in PHP. Friends in need can refer to the following code: /* * * InsertModel(), using reflection, slightly less efficient* @param class $mod...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn