On May 4, 9:47*am, Ronald Raygun <inva...@domain.comwrote:
I want to store objects in ana array and then iterate through the array,
retrieving a (reference) to each object in the array, and calling a
method on the array. I am not sure how to do it, but this is pseudocode
of what I want to do:
<?php
* * $m_fieldItems = createObjects();
* * $outstr = '';
* * for($i=0; $i < count($m_fieldItems); $i++)
* * * $outstr .= $m_fieldItems[$i]->Method1()
* * return $outstr;
?>
My main questions about the code is this:
1). to the object (good), or am I inadvertendly causing a copy of the
object being retrieved to be created (bad and clumsy). If I am causing a
copy of the object at the ith position to be created, how do I enforce
that I return the object by REFERENCE rather than by VALUE?
Are there any other 'gotchas' I need to be aware of?
Are you using PHP 4? If so then the problem will be in the function
that builds your array of objects in the first place. In PHP 4 the =
operator causes an object copy to be created. This catches a lot of
guys who have OO experience out as it's not what happens in most other
OO languages that I'm aware of.
One approach is to use =& to build your array instead of =, ad =&
causes a reference to be created and assigned instead of the object to
be copied.
But if you're doing any kind of meaningful OO work then by far the
better option is to upgrade to PHP 5. The object model in 5 is far
more complete than the one in 4, with public, protected and private
members, class constants, static members, uniform constructors and
destructors, exceptions (if you like that sort of thing :) ) and, most
importantly, objects are copied by reference by default.