note 54196 added to language.oop5
| From: | zabmilenko at hotmail dot com | Date: | Mon, 27 Jun 2005 07:27:54 +0000 |
| Subject: | note 54196 added to language.oop5 | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-90996@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/language.oop5.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54196
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54196&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54196&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54196&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54196&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54196&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54196&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54196&report=yes
Search -- http://master.php.net/manage/user-notes.php