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条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)