sheppardzwc Posted December 2, 2009 Share Posted December 2, 2009 Hello, I've been trying many variants to initialize a class via a function or a included file. First, I tried creating the core.php file which does some internal functions, but at the bottom, added: $db = new DB('localhost', 'auser', 'apass', 'adb', 'aport'); $db->connect(); To automatically connect every time that core.php is included. But when I included this file in my test.php file, it did not initialize the class. I then tried creating a separate class, and a function to initialize it, and it still didn't show up. Other than putting $db = bla at the beginning of EVERY file, how can I make this work? Quote Link to comment Share on other sites More sharing options...
Alex Posted December 2, 2009 Share Posted December 2, 2009 If you're putting that in core.php the include must be before you try to access the object. Quote Link to comment Share on other sites More sharing options...
FaT3oYCG Posted December 2, 2009 Share Posted December 2, 2009 example database connection file: <?php /* Includes the settings file so the database, its username and password can be accessed */ include('settings.php'); /* Created the DBCon class which should only include functions */ /* that access the database to retreive data and such */ class DBCon { /* Creates a blank variable for the connection */ var $connection; function DBCon() { /* Creates a connection to the databse */ $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error()); /* Selects the database defined in the constants */ mysql_select_db(DB_NAME, $this->connection) or die(mysql_error()); } /* Carry out a query on the database. */ function query($query) { return mysql_query($query, $this->connection); } function getRows($result) { return mysql_numrows($result); } function getArray($result) { return mysql_fetch_array($result); } }; /* Initialise a database connection for any extensions of this class */ $DBCon = new DBCon; ?> p.s. to define things such as DB_USER then you would put something like. <?php define('DB_USER', 'root'); ?> in the settings.php file. EDIT: Please note that the connection to the database will be initiated when the DBCon function is called when a new instance of the class is created. i.e. at the bottom of the file, this means any further classes or files that include this file would be able to access the database. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.