首页 >后端开发 >php教程 >php使用反射插入对象示例分享_PHP

php使用反射插入对象示例分享_PHP

WBOY
WBOY原创
2016-06-01 11:55:27851浏览

复制代码代码如下:
/** 
    * 插入insertModel(),利用反射,效率稍差
    * @param class $model 对象
    * @param bool $is_returnLastInsertId 是否返回添加ID
    * @return int 默认返回成功与否,$is_returnLastInsertId 为true,返回添加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);
            $属性=$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,',');
            这个 $- >sql = "插入 {$tName} ({$fields}) 值 ({$vals})";
            if($is_returnLastInsertId){
                $this->conn->exec($ this->sql);
                $lastId = (int)$this->conn->lastInsertId();

                return $lastId;
            }  else {
                $行= $this->conn->exec($this->sql);

                return $row;
            }
        } catch (Exception $exc) {
            echo $ exc->getMessage();
        }
    }

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn