duanhongxian6982 2016-06-02 15:59
浏览 55
已采纳

如何解决oop错误

I'm newbie here. I tried to solve this for a day and searching all the way but I still couldn't.

The error shown up

Notice: Undefined variable: db (in dbFunction)

Fatal error: Call to a member function query() on a non-object (in dbFunction)

and code is

dbConnect.php

class dbConnect{

    public $db;

    public function __construct(){
        $db = new mysqli("localhost", "root", "", "onlineshopping");
        $db->set_charset("charset");
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s
", mysqli_connect_error());
            exit();
        }
    }   
}

dbFunction

class dbFunction extends dbConnect {  

    function __construct() {  

    }  

    public $db;

    public function UserRegister($fname, $lname, $tel, $email, $pass){
        $pass = md5($pass);  
        $db->query("INSERT INTO member(fname, lname, tel, email, password) values('".$fname."','".$lname."','".$tel."','".$email."','".$pass."')") or die(mysqli_error());  
        return $db;     
    }  
}
  • 写回答

4条回答 默认 最新

  • doublestar2014 2016-06-02 16:11
    关注

    First of all, your $db is a local variable in the __construct() method and not a class property and second, as pointed by @wogsland it gets overwritten by the child.
    You might want to review a bit the OO basics

    dbConnect.php

    class dbConnect{
    
        public $db;
    
        public function __construct(){
            $this->db = new mysqli("localhost", "root", "", "onlineshopping");
            $this->db->set_charset("charset");
            if (mysqli_connect_errno()) {
                printf("Connect failed: %s
    ", mysqli_connect_error());
                exit();
            }
        }   
    }
    

    dbFunction

    class dbFunction extends dbConnect {  
    
        public function UserRegister($fname, $lname, $tel, $email, $pass){
            $pass = md5($pass);  
            $this->db->query("INSERT INTO member(fname, lname, tel, email, password) values('".$fname."','".$lname."','".$tel."','".$email."','".$pass."')") or die(mysqli_error());       
        }  
    }
    

    Notice the replacement of $db with $this->db in both methods.

    edit:

    My post was an exact answer to your question but, as others have pointed in comments, there are quite a few things you need to improve and my hope was that this code is for your own personal play not something for 'production'.

    So, directly related to the code example, two obvious things you might want to expand:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题