View Single Post
Old 08-23-2009, 02:17 PM   #1 (permalink)
Nora
The Visitor
 
Join Date: Aug 2009
Location: The Netherlands
Posts: 3
Thanks: 0
Nora is on a distinguished road
Help Accessing Mysqli From Different Class

I'm just getting started with OOP and I'm having trouble connecting to the database.

I made a class that would allowed to connect to the database but I had to use 'global $mysqli' in every method to avoid the non-object errors.
Now, I'm experimenting with a singleton pattern but I have no idea how to access the database connection from another class.

Database class:
PHP Code:
class database{

    private 
$mysqli;
    private function 
__construct(){
        
$this->mysqli = new mysqli($this->host$this->user$this->pass$this->name);        
    }

    public static function 
getInstance(){    
        if(
is_null(database::$instance)){
            
database::$instance = new database();
        }
        return 
database::$instance;    
    }

New class where it all goes wrong:
PHP Code:
class {
    public function 
select($sql){
        
$query $mysqli->query($sql);
    }

It works fine outside the classes using:
$db = database::getInstance();

I'd really appreciate it if someone could point me in the right direction.
Nora is offline  
Reply With Quote