|
Posted by Bogdan Ribic on 10/02/65 11:30
Morgan Doocy wrote:
> I'm trying to figure out if PHP has the facility to reference containing, non-parent objects. I have three classes, embedded hierarchically, but which are NOT extended classes of their containing objects. I'd like to be able to reference variables in the higher-level objects from the lower-level objects.
>
> To illustrate:
>
> <?php
>
> class Country {
> var $name;
> var $states;
>
> function Country($name = '', $states = array()) {
> $this->name = $name;
> $this->states = $states;
> }
> }
>
> class State {
> var $name;
> var $cities;
>
> function State($name = '', $cities = array()) {
> $this->name = $name;
> $this->cities = $cities;
> }
> }
>
> class City {
> var $name;
>
> fuction City($name = '') {
> $this->name = '';
> }
>
> function name_with_state() {
> return "$this->name, " . /* parent node reference */->name;
> }
> }
>
> $countries = array (
> 'USA' => new Country('United States',
> array (
> 'WA' => new State('Washington',
> array (
> 'SEA' => new City('Seattle'),
> 'GEG' => new City('Spokane')
> )
> ),
> 'CA' => new State('California',
> array (
> 'LAX' => new City('Los Angeles'),
> 'SFO' => new City('San Francisco')
> )
> )
> )
> )
> );
>
> echo $countries['USA']->states['WA']->cities['SEA']->name_with_state();
> // Output: 'Seattle, Washington'
>
> ?>
>
> Obviously, just extending Country doesn't make sense: a State isn't a type of Country, and a City isn't a type of State -- but States are part of Countries, and Cities are part of States. Plus, if City was just an extended State (which in turn is an extended Country), it would contain both a $states and a $cities variable. Which doesn't make sense.
>
> What, if anything, do I replace /* parent node reference */ with in City::name_with_state()?
>
> Thanks,
>
> Morgan
I suspect you want the functionality of Java embedded clases, where
embedded class can access fields of its container. If that's what you
mean, then sorry, PHP doesn't have that. You would have to keep a
reference ro parent object as a variable in child object, ie your City
should have a var $_state variable, etc.
--
Open source PHP code generator for DB operations
http://sourceforge.net/projects/bfrcg/
[Back to original message]
|