Jump to content

[SOLVED] Using other class objects inside another class


ChadNomad

Recommended Posts

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?

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();
    }
}
?>

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.