Php object programming BUG! I wrote a db chain operation model object. the following code shows the bug (only a small segment is extracted ).
public function insert(Array $c, $p = 'INSERT') { if(!is_null($this->px)) return $this; function i( $c, $e = ',') { $d = ''; foreach ($c as $val) { # code... $d .= $e . '('; foreach ($val as $valTow) { $d .= '"' . $valTow . '",'; $d = trim($d, ','); } // var_dump($d); $d .= ')'; } return rtrim($d, ')'); } $n = '('; $d = '('; foreach ($c as $key => $value) { $n .= '`' . $key . '`,'; if(is_array($value)) { $d = i($value); } else { $d .= '"' . $value . '",'; } } $n = rtrim($n, ',') . ')'; $d = rtrim($d, ',)'); $d .= ')'; $this->insert = $p . ' INTO ' . $this->tableName . " {$n} VALUES {$d} "; $this->px = __METHOD__; return $this; }
Watch carefully and you will find that a function is defined in the method. if this function is called at the same time, an I function cannot be repeatedly defined error will pop up!
The solution is simple! That is, write the I function to another place or write it as an object method;
Therefore, we recommend that you do not define the function in the method that is run multiple times!
This can be written if the object is called only once!
You can easily solve the problem by making the following changes! (This is only one solution !)
public function insert(Array $c, $p = 'INSERT') { if(!is_null($this->px)) return $this; $n = '('; $d = '('; foreach ($c as $key => $value) { $n .= '`' . $key . '`,'; if(is_array($value)) { $d = $this->i($value); } else { $d .= '"' . $value . '",'; } } $n = rtrim($n, ',') . ')'; $d = rtrim($d, ',)'); $d .= ')'; $this->insert = $p . ' INTO ' . $this->tableName . " {$n} VALUES {$d} "; $this->px = __METHOD__; return $this; } private function i( $c, $e = ',') { $d = ''; foreach ($c as $val) { # code... $d .= $e . '('; foreach ($val as $valTow) { $d .= '"' . $valTow . '",'; $d = trim($d, ','); } // var_dump($d); $d .= ')'; } return rtrim($d, ')'); }