note 54196 deleted from language.oop5 by felipe
| From: | felipe@php.net | Date: | Mon, 24 Mar 2008 22:11:13 +0000 |
| Subject: | note 54196 deleted from language.oop5 by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137470@lists.php.net to get a copy of this message | ||
Note Submitter: zabmilenko at hotmail dot com
----
Dynamic instantiation trick:
<?php
class CITY
{
private $population;
public function __construct($cityname)
{
// Load some city-specific data
}
public function population($demographic = 'all')
{
return $this->population[$demographic];
}
}
class COUNTRY
{
private $code = null;
private $cities = array();
public function __construct($code)
{
$this->code = $code;
}
public function city($cityname)
{
if (!$this->cities[$cityname])
{
$this->cities[$cityname] = new CITY($cityname);
}
return $this->cities[$cityname];
}
}
class WORLD
{
private $countries = array();
public function country($code = 'us')
{
if (!$this->countries[$code])
{
$this->countries[$code] = new COUNTRY($code);
}
return $this->countries[$code];
}
}
$world = new WORLD;
// Load the country AND city object
echo
$world->country('us')->city('seattle')->population('employed');
// Country US is already loaded, only need to load a new city object.
echo $world->country('us')->city('new york')->population();
?>
This example uses Countries and Cities wrapped around a World object. You can use any schema you
want, however. Think: Domain->Subdomain->Node or
KINGDOM->PHYLUM->CLASS->ORDER->FAMILY->GENUS->SPECIES
What is happening here is that a private array is storing the class objects. Only the class objects
that are needed are loaded, when they are needed. You can nest this many many times as needed.
You see that the array is never exposed. Each function reference will check to see if a new class
object is needed and create it if necessary.
This is literally as simple as it looks. Hope it helps someone out.