Interaction between classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
LiveFree
Forum Contributor
Posts: 258
Joined: Tue Dec 06, 2005 5:34 pm
Location: W-Town

Interaction between classes

Post by LiveFree »

Hey All,

I am building a site and, as Im looking to develop my OOP skills, have decided to do the majority in OOP. So far I have a templating class (works), an SQL layer (working so far), and a site maitenance class (AAAANT!).

My index.php looks like this:

Code: Select all

include('classes/template.class.php');
include('classes/mysql.class.php');
include('classes/maitenance.class.php');

// template + modular code here

$ops->getNews();

// template code here
I use the $mysql->query() function I made in the SQL layer in the maitenance.class file, but when I try to execute the getNews() func, I get an 'atal error: Call to a member function on a non-object' error

Now the class is initialized (the sql layer) before it is used in the maitenance file and the DB connect and select are executed before as well (and tested, there is a full connection to the MySQL server)

Now in the getNews() func I have this:

Code: Select all

function getNews()
  	{
		$mysql->query('SELECT * FROM ' . $this->news_table . ' LIMIT '. $this->num_news, $sql) or die (mysql_error());
		
		$output = '';
		
		while ($row = mysql_fetch_array($sql))
		{
		  $output .= "<h2>{$row['title']} - {$row['date']}</h2>";
		  $output .= "<p>{$row['maintext']}</p>";
		  $output .= "<hr /><br />";
		}
		
		return $output;    
	}
Note the use of the $mysql->query()


Question: Is there a specific action to perform to have 2 classes interact?

Thanks and sorry for the long post :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You can either use a ServiceLocator/Registry type object (or global, or passed argument) to bring the $mysql instance into the function. There's also passing the object during creation and making it a property of the current object.
LiveFree
Forum Contributor
Posts: 258
Joined: Tue Dec 06, 2005 5:34 pm
Location: W-Town

Post by LiveFree »

Haha

Code: Select all

global $mysql;
Worked perfectly for me! Thanks for the suggestion feyd :)
Post Reply