我遇到以下问题,我的SQLBuilder的那些方法是一样的,我该怎么做才能减少代码?
public function select($fields){
if(is_array($fields)){
$this->fields = implode(',', $fields);
} else {
$this->fields = $fields;
}
return $this;
}
public function from($tables){
if(is_array($tables)){
$this->tables = implode(',', $tables);
} else {
$this->tables = $tables;
}
return $this;
}
答案 0 :(得分:1)
创建一个公共私有方法来执行处理,然后创建使用它们的公共方法
public function select($fields){
return $this->builddata($fields, 'fields');
}
public function from($tables){
return $this->builddata($tables, 'tables');
}
private function builddata($data, $storage) {
if(is_array($data)){
$data = implode(',', $data);
}
$this->$storage = $data; // variable variable
return $this;
}
答案 1 :(得分:0)
或
public function action($data, $type){
if(is_array($data)){
$this->$type = implode(',', $data);
} else {
$this->$type = $data;
}
return $this;
}
然后
$this->action($data, 'select');