php类显示空查询

时间:2016-06-01 17:56:36

标签: php oop

这是我的班级:

<?php
class Query {
    protected $_link;
    protected $_result;
    protected $_query;

    public function __construct($query) {
        $_link=  mysqli_connect('localhost', 'root', '', 'mismatch') 
            or die('Unable to connect database');
        $this->_query=$query;
        $_result = mysqli_query($_link, $_query)
                or die('unable to enter the query');
        }
        protected function getResult(){
            return $this->_result;
        }
}

?>

我以这种形式在索引文件中导入了我的类:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <h1> Become the member here</h1>

<?php 
   require_once 'C:/xampp/htdocs/mismatch/cls/csl_Query.php';
   $q='SELECT * FROM `user`';
   $query1=new Query($q);
   echo $query1->getResult();

?>


    </body>
</html>

在浏览器中打开文件时显示以下错误:

注意:未定义的变量:第11行的C:\ xampp \ htdocs \ mismatch \ cls \ csl_query.php中的_query

警告:mysqli_query():第11行的C:\ xampp \ htdocs \ mismatch \ cls \ csl_query.php中的空查询 无法输入查询

请显示我的错误

1 个答案:

答案 0 :(得分:3)

您缺少一些$this->

要使getResult()方法找到$this->_result,您需要在构造函数方法中使用变量前面的$this->

如果没有$this->,则引用一个仅存在于构造函数方法

中的局部变量
<?php
class Query {
    protected $_link;
    protected $_result;
    protected $_query;

    public function __construct($query) {
        $this->_link=  mysqli_connect('localhost', 'root', '', 'mismatch') 
        or die('Unable to connect database');
        $this->_query=$query;
        $this->_result = mysqli_query($_link, $_query)
            or die('unable to enter the query');
    }

    protected function getResult(){
        return $this->_result;
    }
}
?>
  

在属性名称中使用下划线也有点旧学校(通常用于表示Private属性)。这不再是真的了。