Home  >  Article  >  Backend Development  >  为甚麽这个变量为null

为甚麽这个变量为null

WBOY
WBOYOriginal
2016-06-23 14:02:12869browse

class my_connect{       private $conn;       private  function get_conn() {            $conn=new mysqli('localhost',"root","","test",3306);            $conn->set_charset("utf8");            return $conn;        }        private  function __destruct() {            if(isset($this->conn)){                $this->conn->close();            }        }        static function get_instance() {            $new_conn=new my_connect() ;            $conn=$new_conn->get_conn() ;            return $conn;        }    } 当我执行 $conn=my_connect::get_instance(); 到析构函数的时候 $conn变量为null也就是没有执行  $this->conn->close();


回复讨论(解决方案)

设置的时候,是否要使用$this->呢?

明显这一步是错的,这一步判断该变量是否已定义了,private $conn;,这边你已经定义过了,虽然什么值都没有

if(isset($this->conn)){


改下就好
if($this->conn){

我去,看错了。。。。

get_conn 是私有方法,

private  function get_conn

改为 
public  function get_conn

即可

这个类你可以优化优化,还有待优化

没用过mysqli,为什么不直接用mysql_connect呢

围观一下

Statement:
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