php使用反射插入对象示例分享
程序员文章站
2023-11-22 15:48:34
复制代码 代码如下:/** * 插入insertmodel(),利用反射,效率稍差 ...
复制代码 代码如下:
/**
* 插入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();
}
}
上一篇: 干货!教大家如何选择Vue和React