Hi all,

How come this class doesnt connect to the database..?

class credentials {

private static $config = array();

const DB_USER = 'root'; 
const DB_PASS = ''; 
const DB_HOST = 'localhost';    
const DB_NAME = 'dev_dcs';

public function __construct() {

    self::$config['user'] = self::DB_USER;
    self::$config['pass'] = self::DB_PASS;
    self::$config['host'] = self::DB_HOST;
    self::$config['name'] = self::DB_NAME;

    return $this->config;

}

}

// DATABASE ACCESS :    
class database extends credentials {

public function __construct()
{
    try 
    {
        if ( $this->database = 
        new MySQLi( parent::DB_HOST, parent::DB_USER, parent::DB_PASS, parent::DB_NAME ) === true ) 
        {
            echo 'DB CLASS VIRKER.';    
            return $this->database;
        }           
        else 
        {   
            throw new Exception( "Database connection error" );
        }           
    }
    catch( Exception $e ) 
    {
        echo $e->getMessage();
    }       
}

}

EDIT:

EDIT:

Arh I had 3 equal signs to true, which made an error i think..

Recommended Answers

All 3 Replies

Member Avatar for diafol

Do you need to declare the $database variable in your class before you assign it?

Did you error dissapear ?

@diafol : Dont I need to assign it to a variable to be able to return it from the class and use it?

I changed it to this, and its working now :

class configuration {

private static $config = array();

const DB_USER = 'root'; 
const DB_PASS = ''; 
const DB_HOST = 'localhost';    
const DB_NAME = 'dev_dcs';

public function __construct() {

    self::$config['user'] = self::DB_USER;
    self::$config['pass'] = self::DB_PASS;
    self::$config['host'] = self::DB_HOST;
    self::$config['name'] = self::DB_NAME;

    return $this->config;

}

}

// DATABASE CONNECTION :    
final class database extends configuration {

private static $database;

public function __construct()
{
    try 
    {
        if ( self::$database = new MySQLi( parent::DB_HOST, parent::DB_USER, parent::DB_PASS, parent::DB_NAME ) == true )
        {
            echo 'DB CLASS VIRKER.';    
            return self::$database;
        }           
        else 
        {   
            throw new Exception( "Database connection error" );
        }           
    }
    catch( Exception $e ) 
    {
        echo $e->getMessage();
    }       
}

}

But help with "my logic" is appreciated - Is it an ok approach to to it like this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.