dongyan5815 2013-08-04 13:36
浏览 39
已采纳

OOP类继承错误[关闭]

<?php

// Forum Configuration
define('DB_HOST','localhost'); // Database Hostname
define('DB_USER','root'); // Database Username
define('DB_PASSWORD',''); // Database Password
define('DB_NAME','ultraforum'); // Database Name
define('WEB_NAME','Website Name'); // Website Name
define('WEB_TITLE','Website Title'); // Website Title


// Do not modify anything under this line :)

class db {

    var $dbhost;
    var $dbuser;
    var $dbpassword;
    var $dbname;
    var $query;

    function connect() {
        $this->db =
            new mysqli($this->dbhost, $this->dbuser, $this->dbpassword, $this->dbname);
    }

    function __construct() {
        $this->dbhost = DB_HOST;
        $this->dbuser = DB_USER;
        $this->dbpassword = DB_PASSWORD;
        $this->dbname = DB_NAME;
    }
}

And my Forum class extending DB

class forum extends db{

    public function __construct() {
        parent::__construct();
    }

    function displayInfo () {
        $this->forumInfo =
        $getInfo = $db->db->query("SELECT * FROM threads");
        while($getI = $getInfo->fetch_object()) {
            return $getI->Title;
        }
    }
}

With the second class, I want to get all of the threads from my mysqli database. I extended it from the first class because I wanted the connection information. This is how im implementing the class:

 $ThreadInfo = new forum;
 $ThreadInfo->displayInfo();

But I get

Notice: Undefined property: forum::$db on line 42
Fatal error: Call to a member function query() on a non-object in on line 42

  • 写回答

4条回答 默认 最新

  • doukengsha9472 2013-08-04 13:43
    关注

    Firstly, your connection is not instantiated, you need to call connect() in your db class.

    function __construct() {
        $this->dbhost = DB_HOST;
        $this->dbuser = DB_USER;
        $this->dbpassword = DB_PASSWORD;
        $this->dbname = DB_NAME;
        $this->connect();
    }
    

    Secondly you want to access $db in class' scope:

    $getInfo = $this->db->query("SELECT * FROM threads");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?