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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.