ChadNomad Posted July 14, 2008 Share Posted July 14, 2008 Still getting to grips with my transition to OOP. I have a simple database class like this: <?php // Database constants define("DB_SERVER", "localhost"); define("DB_USER", "root"); define("DB_PASS", ""); define("DB_NAME", "my_db"); class MySQL { function connect() { mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die (mysql_error()); mysql_select_db(DB_NAME) or die (mysql_error()); } function query($sql) { $mysql_query = mysql_query($sql) or die (mysql_error()); return $mysql_query; } function fetchrow($sql) { $mysql_rows = mysql_fetch_row($sql) or die (mysql_error()); return $mysql_rows; } function fetcharray($sql) { $mysql_array = mysql_fetch_array($sql) or die (mysql_error()); return $mysql_array; } function fetchnum($sql) { $mysql_num = mysql_num_rows($sql) or die (mysql_error()); return $mysql_num; } } // Instantiate the class for procedural use $db = new MySQL(); // Connect to the database $db->connect(); ?> Now I'm using another class I need to use the db object. The only way I've figured this out is to instantiate it again within the class, like this: // Headers class. Used to find out age information class SystemInformation { // Header information function head_content() { $db = new MySQL(); $this->head_information_query = $db->fetch_array("SELECT * FROM system WHERE active='1'"); Is there a way to make the $db object global (not sure if global is the right word) so it can be used throughout the entire SystemInformation class? Quote Link to comment Share on other sites More sharing options...
coder_ Posted July 14, 2008 Share Posted July 14, 2008 Maybe you should try this: <?php class SystemInformation { private $db; public function __construct() { require_once('Mysql.php'); $this->db =& new MySQL(); } public function fetchSystemInfos() { $this->db->connect(); } } ?> Quote Link to comment Share on other sites More sharing options...
ChadNomad Posted July 14, 2008 Author Share Posted July 14, 2008 Just what I was looking for, thanks! 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.