aha. So Tony,
how is this:
class Person {
function doStuff () {
....
$objAddress =& singleton::getInstance('address');
$address = $objAddress->getPrimaryAddress($customer_id);
....
} // doStuff
} // end class Person
class singleton
// ensure that only a single instance exists for each class.
{
function &getInstance ($class, $arg1=null)
// implements the 'singleton' design pattern.
{
static $instances = array(); // array of instance names
if (array_key_exists($class, $instances)) {
// instance exists in array, so use it
$instance =& $instances[$class];
} else {
// load the class file (if not already loaded)
if (!class_exists($class)) {
switch ($class) {
case 'date_class':
require_once 'std.datevalidation.class.inc';
break;
case 'encryption_class':
require_once 'std.encryption.class.inc';
break;
case 'validation_class':
require_once 'std.validation.class.inc';
break;
default:
require_once "classes/$class.class.inc";
break;
} // switch
} // if
// instance does not exist, so create it
$instances[$class] = new $class($arg1);
$instance =& $instances[$class];
} // if
return $instance;
} // getInstance
} // singleton
new Person();
Shorter and faster than:
class Person {
public function __construct(Address $address) {
$this->address = $address;
}
function doStuff () {
....
$address = $this->address->getPrimaryAddress($customer_id);
....
} // doStuff
} // end class Person
$address = new Address;
new Person($address);