PHP 5.5
I'm doing a bunch of passing around of objects with the assumption that they will all maintain their identities - that any changes made to their states from inside other objects' methods will continue to hold true afterwards. Am I assuming correctly?
I will give my basic structure here.
class builder {
protected $foo_ids = array(); // set in construct
protected $foo_collection;
protected $bar_ids = array(); // set in construct
protected $bar_collection;
protected function initFoos() {
$this->foo_collection = new FooCollection();
foreach($this->food_ids as $id) {
$this->foo_collection->addFoo(new foo($id));
}
}
protected function initBars() {
// same idea as initFoos
}
protected function wireFoosAndBars(fooCollection $foos, barCollection $bars) {
// arguments are passed in using $this->foo_collection and $this->bar_collection
foreach($foos as $foo_obj) { // (foo_collection implements IteratorAggregate)
$bar_ids = $foo_obj->getAssociatedBarIds();
if(!empty($bar_ids) ) {
$bar_collection = new barCollection(); // sub-collection to be a component of each foo
foreach($bar_ids as $bar_id) {
$bar_collection->addBar(new bar($bar_id));
}
$foo_obj->addBarCollection($bar_collection);
// now each foo_obj has a collection of bar objects, each of which is also in the main collection. Are they the same objects?
}
}
}
}
What has me worried is that foreach
supposedly works on a copy of its arrays. I want all the $foo and $bar objects to maintain their identities no matter which $collection object they become of a part of. Does that make sense?
EDIT: My understanding is that using the clone
keyword is the only way to really copy an object in PHP 5+. Using the assignment operator basically just creates another reference to the same object. I'm hoping that return values and foreach
also work that way.
&$object
to not pass the object by value. Passing a copy and manipulating it will have effect in the scope of the method.&
with objects. I suppose that fairly soon I will find out for myself once my code is wired and I start testing it. SO: stackoverflow.com/questions/2715026/…