在类对象中调用函数时出错

时间:2012-05-14 03:10:26

标签: php

我有一个示例代码:

class DBConnect {
    private $connect = null;
    private $query = null;
    public $result = 0;
    public $data = null;
    public $_result;

    function connect() {
        $this->connect = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die("Can't connect database");
        mysql_query("set names 'utf8'");
        mysql_select_db(MYSQL_NAME, $this->connect);
    }

    function close() {
        if($this->connect) {
            mysql_close($this->connect);    
        }
    }

    function query($sql) {
        $this->query = mysql_query($sql);
        if(!$this->query) {
            echo "Error: " . mysql_error();
            exit;
        }
    }

    function get_data($category_id) {
        $sql = 'SELECT id, name FROM category WHERE id='.$category_id;
        query($sql); // This is error
        $row = mysql_fetch_object($query);
        $data = $row->category;
        return $data;
    }
}

当我运行debug时,错误是:Call to undefined function query() in line...,如何解决?

2 个答案:

答案 0 :(得分:2)

您可以更改功能查询 - > QUERY1

function query1($sql) { 
        $this->query = mysql_query($sql); 
        if(!$this->query) { 
            echo "Error: " . mysql_error(); 
            exit; 
        } 
    } 

然后:

function get_data($category_id) { 
        $sql = 'SELECT id, name FROM category WHERE id='.$category_id; 
        $this->query1($sql); // Error has repair
        $row = mysql_fetch_object($query); 
        $data = $row->category; 
        return $data; 
    } 

答案 1 :(得分:-1)

在代码的这一部分

function get_data($category_id) {
        $sql = 'SELECT id, name FROM category WHERE id='.$category_id;
        $this->query($sql); // This is error -> this is suppose to
        $row = mysql_fetch_object($this->query); // this also
        $data = $row->category;
        return $data;
    }