Jump to content

Intialization of a Class


sheppardzwc

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/183780-intialization-of-a-class/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.