I'm trying to figure out why this code won't work.
I have 5 or 6 different types of collection objects all are subclassed
from the object below. Each collection can contain other collections or
just objects of a particular class.
After the data is inserted into the classes the "path" to a particular
collection gets lost. So I need a look-up table or a function to find the object.
That's what I tried to do with the $GLOBALS['object_reference'][$this->name]=&$this;
variable below.
<pre>
<?
class collection
{
var $name;
var $objects;
function collection($n)
{
if(!isset($GLOBALS['object_reference']))
$GLOBALS['object_reference']=array();
$this->set_name($n);
$GLOBALS['object_reference'][$this->name]=&$this;
$this->objects=array();
}
function get_name()
{
return($this->name);
}
function set_name($n)
{
$this->name=$n;
}
function add($o)
{
if(isset($o->name))
$this->objects[$o->name]=$o;
else
return false;
return true;
}
}
</pre>
$a=& new collection("Collection A");
$b=& new collection("Collection B");
$c=& new collection("Collection C");
$a->add($c);
$GLOBALS['object_reference']["Collection C"]->add($b);
echo "<pre>";
print_r($GLOBALS['object_reference']);
echo "</pre>";
echo "<pre>";
print_r($a);
echo "</pre>";
?>
When I dump $a, collection B is not there.
collection Object
(
[name] => Collection A
[objects] => Array
(
[Collection C] => collection Object
(
[name] => Collection C
[objects] => Array
(
)
)
)
)
When I dump $GLOBALS['object_reference'] it is there, although it still is not in collection A.
Array
(
[Collection A] => collection Object
(
[name] => Collection A
[objects] => Array
(
[Collection C] => collection Object
(
[name] => Collection C
[objects] => Array
(
)
)
)
)
[Collection B] => collection Object
(
[name] => Collection B
[objects] => Array
(
)
)
[Collection C] => collection Object
(
[name] => Collection C
[objects] => Array
(
[Collection B] => collection Object
(
[name] => Collection B
[objects] => Array
(
)
)
)
)
)
For this simple example I could just write
$a->objects["Collection C"]->add($😎;
and everything works fine.
However as collections get added the "path" to them gets lost.
In other words I don't know that collection C is inside of collection B when the user asks to see collection C.
So I thought I would use an array of references to look-up the object and get or set what is needed.
I also wrote a function to find the object.
<pre>
function &findObject($obj,$name)
{
if(is_array($obj->objects))
{
foreach($obj->objects as $o)
{
if($o->name == $name) return($o);
findObject($o,$name);
}
}
}
</pre>
I could write: $obj=findObject($a,"Collection C");
While this will find the object. I have the same problem when I want to change the object.
I hope I explained this OK.
Any one have any suggestions?
Doug