0

I want to call a PHP class in another class and get the following error:

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

Class 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

    }
}

Class 2:

class DB {

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

I call it:

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

What I have to do to call them into each other? Or is there a other way to do that. Thanks a lot for help!

fteinz
  • 1,085
  • 5
  • 15
  • 30
  • possible duplicate of [What is a class in PHP?](http://stackoverflow.com/questions/2206387/what-is-a-class-in-php) – Ryan Jan 14 '15 at 21:25
  • looks to me that $db is not visible outside of logmein::dbconnect – Jasen Jan 15 '15 at 07:35

2 Answers2

1

The $db object falls out of scope from dbconnect() to login(). Set it as a class property instead so you can access it anywhere in your class:

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

    }
}
mopo922
  • 6,293
  • 3
  • 28
  • 31
0

You need to be sure that the DB is accessible across your class functions, so it needs to be stored in a class property.

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

    }
}

That being said, this setup is tightly coupling your database with the login. Consider looking into 'dependency injection' and other ways to keep your code components separate.

Jesse Kernaghan
  • 4,544
  • 2
  • 18
  • 25