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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号