Returns by reference is a bad practice. Don’t do it unless you have a very specific reason for it. You also need to check if your function is even returning an array - it could be returning false.
//getObjectArray() retrieves an array of objects
$objArr = getObjectArray();
if (is_array($objArr)) {
foreach($objArr as $obj) {
echo "Name:" . $obj->name;
echo "Surnam:". $obj->surname;
}
} else {
echo 'no results';
}
I have special reason to do so. Developing an MVC component for Joomla 1.5. Due to the implementation of their API, references are necessary to prevent server overheads. Particularly with large objects, performance can be affected.
Any help on how to eliminate the warning will be much appreciated
If the function does not return something iterable, it does give that error. Assuming it returns an array without actually checking doesn’t change that…
It does return an array which I can iterate through but that warning is still output. I stated the assumption so we dont focus on what is returned but on the specific warning and if it can be eliminated
Objects in PHP are references by default. You do not need to implicitly use the pass by reference operator, nor should you. Also, with non-objects PHP performs copy on edit at an engine level, so the memory impact isn’t there.
And, to be blunt, if you are having difficulty with a foreach iteration I sincerely doubt you have a technical reason for it.
In the code I gave you a way to test to see if you where getting what you expect - an array of objects. You need to test for that before iterating or the warning will pop up. Joomla doesn’t exactly have the most consistent API out there (neither does core PHP for that matter), so I’m guessing the function is returning boolean “false” to alert you that there are no objects found. You can’t iterate over “false” so foreach emits a warning.
So check and see what the function is actually returning.
Many thanks for your replies and tips. Though my question was focused more on the warning, I do appreciate that everyone is trying to help . I also agree on var_dump, xdebug, print_r etc…invaluable debugging tools!
Not too sure, Salathe. Out of frustration,I re-wrote that section of the code and revised the associated functions. I am convinced it is the same, but evidently it was not…because now it works with no warnings