Accessing sibling objects from inside an object
I had some problem formulating the question in the title, but i hope you get me with a bit of example code.
Basically:
In a objectoriented project i want to access an object that is defined in the "parent" object. consider this snippet:
class Bar
{
public $var;
public function Bar()
{
$this->var = 'value';
}
}
class Bogus
{
public function Bogus()
{
//Here i want to access the methods and vars of obj1 in the "parent" objec开发者_开发百科t
}
}
class Foo
{
public $obj1,$obj2;
function Foo()
{
$this->obj1 = new Bar();
$this->obj2 = new Bogus();
}
}
as you can see the "child" object are not really childs in the sense that they extend the "parent" class but only objects instanciated inside an object.
is there any "oh damn thats cool" kinda way to do this or do i have to pass the objects to eachother like:
$this->obj2 = new Bogus($this->obj1);
or make use of global object, instanciating objects outside the class:
global $bar,$bogus;
class Foo
{
public $obj1,$obj2;
function Foo()
{
global $bar,$bogus;
$this->obj1 = $bar = new Bar();
$this->obj2 = $bogus = new Bogus();
}
}
I hope you can understand what im getting at ;)
I think you might want to use a Singleton Pattern (Creating the Singleton design pattern in PHP5).
Although you also might want to do a little more research on design patterns in general, specifically you might want to take a look at Is there a use-case for singletons with database access in PHP?
I would give the parent object to the children, maybe not by constructor, but a setter. And if the parent is set, then we are able to access its children:
/* in Bogus ... */
public function setParent($parent)
{
$this->parent = $parent;
}
public function getSiblingVar()
{
if (!empty($this->parent->obj1))
{
return $this->parent->obj1->var;
}
return false;
}
/* in Foo ... */
$this->obj1 = new Bar();
$this->obj2 = new Bogus();
$this->obj2->setParent($this);
I would also use some children object variable for the objects, then you can iterate an objects siblings, referencing their parent.
public function getSiblingVar($sibling_id,$var_name)
{
if (!empty($this->parent->children[$sibling_id]))
{
return $this->parent->children[$sibling_id]->getVar($var_name);
}
return false;
}
Are those objects related as same type, same class, or different objects that compose a bigger object ?
Same Type, example nested folders and files in your O.S.
Different Type, compose a bigger item, like class Car composed by Wheels, Motor, etc.
精彩评论