Low cost ecommerce web development India flash website design

How do objects interact?

Aside from inheritance, there are other ways for objects to interact; for example,

one object uses another object. In many ways, such interactions are more important

than inheritance, and this is where the object oriented paradigm shows its real

power.

There are two ways in which one object can use another: aggregation and composition.

Aggregation

Aggregation occurs when one object is given another object on “temporary loan.”

The second object will usually be passed to the first through one of the first's

member functions. The first object is then able to call methods in the second,

allowing it to use the functionality stored in the second object for its own purposes.

A common example of aggregation in action involves a database connection class.

Imagine you pass a database connection class to some other class, which then

uses the database connection class to perform a query. The class performing the

query aggregates the database connection class.

Here's a simple example using the MySQL class, which we'll create in Chapter 3:

File: 13.php

<?php

// Include the MySQL database connection class

require_once 'Database/MySQL.php';

// A class which aggregates the MySQL class

class Articles {

var $db;

var $result;

// Accept an instance of the MySQL class

function Articles(&$db)

{

// Assign the object to a local member variable

$this->db = &$db;

$this->readArticles();

}

function readArticles()

{

// Perform a query using the MySQL class

$sql = "SELECT * FROM articles LIMIT 0,5";

$this->result = &$this->db->query($sql);

}

function fetch()

{

return $this->result->fetch();

}

}

// Create an instance of the MySQL class

$db = &new MySQL('localhost', 'harryf', 'secret', 'sitepoint');

// Create an instance of the Article class, passing it the MySQL

// object

$articles = &new Articles($db);

while ($row = $articles->fetch()) {

echo '<pre>';

print_r($row);

echo '</pre>';

}

?>

In the above example, we instantiate the MySQL class outside the Articles class,

then pass it to the Articles constructor as Articles is instantiated. Articles

is then able to use the MySQL object to perform a specific query. In this case,

Articles aggregates the MySQL object. Figure 2.2 illustrates this relationship with

UML.

website designer freelance ASP PHP ecommerce web developer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110