PHP从另一个类调用类

时间:2015-01-14 21:13:46

标签: php class

我想在另一个类中调用PHP类并收到以下错误:

Fatal error: Call to a member function quote() on a non-object

第1课:

class logmein {

    //Connect DB
    function dbconnect(){
        require_once('class.MySQL.php');
        $db = new Db();    

    }

    //login function
    function login($username, $password){

        //conect to DB
        $this->dbconnect(); 

        // Quote and escape form submitted values
        $name = $db -> quote($username);                    //throwing error
        $email = $db -> quote($password);                   //throwing error

    }
}

第2课:

class DB {

    public function quote($value) {
        $connection = $this -> connect();
        return "'" . $connection -> real_escape_string($value) . "'";
    }
}

我称之为:

$log = new logmein();
$log->login('James Bond', '007');

我需要做些什么来互相称呼他们?或者还有其他方法可以做到这一点。非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

$db对象超出dbconnect()login()的范围。将其设置为类属性,以便您可以在类中的任何位置访问它:

class logmein {

    protected $db; // property available to this class and child classes

    //Connect DB
    function dbconnect(){
        require_once('class.MySQL.php');
        $this->db = new Db(); // say "$this" to refer to it

    }

    //login function
    function login($username, $password){

        //conect to DB
        $this->dbconnect(); 

        // Quote and escape form submitted values
        $name = $this->db->quote($username); // works now
        $email = $this->db->quote($password); // works now

    }
}

答案 1 :(得分:0)

您需要确保可以跨类功能访问数据库,因此需要将其存储在类属性中。

class logmein {
    private $db; //store the database object

    //Connect DB
    function dbconnect(){
        require_once('class.MySQL.php');
        $this->db = new Db();    

    }

    //login function
    function login($username, $password){

        //conect to DB
        $this->dbconnect(); 

        // Quote and escape form submitted values
        $name = $this->db->quote($username);
        $email = $this->db->quote($password);

    }
}

话虽这么说,这个设置将数据库与登录紧密耦合。考虑研究依赖注入'以及保持代码组件分离的其他方法。