当前位置: 移动技术网 > IT编程>开发语言>PHP > php使用反射插入对象示例分享

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

2019年03月28日  | 移动技术网IT编程  | 我要评论

郭德纲上海专场,西安建筑科技大学研究生院,封神太子无敌版

复制代码 代码如下:

/** 
    * 插入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__)).'\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();
        }
    }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网