Interaction between classes is called message passing. For one object to pass a message to another, it has to be aware that it's there to take the message. Here is an example.
Code: Select all
class db
{
var $error;
function db(&$error)
{ $this->error=&$error; }
function queryDB($SQL)
{
/* act as if query failed */
$this->error->testError('The query failed!');
return false;
}
}
class news
{
var $error;
var $db;
function news(&$db, &$error)
{
$this->db=&$db;
$this->error=&$error;
}
function getNews($top_subject, $from_date, $to_date)
{
if($this->db->queryDB($SQL)==false)
{ $this->error->testError('News retrieval failed!'); }
return false;
}
}
class error
{
function testError($err_str)
{ echo "This output is from the error object!\n".$err_str."\n"; }
}
# Instantiate objects
$err=new error;
$db=new db($err);
$news=new news($db, $err);
# Try to get the news
$news->getNews('weather', '1/2005', '3/2005');
Both the news and db objects have a handle to the same error object. How I did this is obvious, but take note of the fact in the constructor declerations that the objects are passed in by reference!
When you run this, you will actually see two messages. In other words, not only is the $news object sending a message to the error object, but the db object is as well. From one request, we were able to start a chain of events that was the message passing amongst multiple objects. As you can see, a message is initially passed from the $news object to the $db object.
Hope that helps,
Cheers