php对象编程的遇到的BUG!

WBOY
Release: 2016-06-23 13:37:53
Original
871 people have browsed it

自己写了个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;    }
Copy after login

仔细观看会发现方法里面定义了一个函数这里如果这个函数同时被调用则会爆出一个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, ')');    }
Copy after login

 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template