php对象编程的遇到的BUG!

自己写了个db链式操作模型对象如下代码所示(只摘取了其中一小段)遇到的bug

    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;
    }

仔细观看会发现方法里面定义了一个函数这里如果这个函数同时被调用则会爆出一个i函数不能被重复定义的错误!

解决办法很简单!就是将i函数写到其他地方或者写成对象方法;

所以建议不要在多次运行的方法里面这么定义函数!

如果对象只被调用一次则可以这么写!

做出如下修改就可以轻松解决问题了!(这只是其中一个解决方案!)

    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, ‘)‘);
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。