0

I'm having to develop a site on PHP 5.1.6 and I've just come across a bug in my site which isn't happening on 5.2+. When using foreach() to iterate over an object, I get the following error: "Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference..."

Does anyone know how to get around this issue?

            $f_type = new Feeding_type_Model;
            $f_type->type = $post['feeding_type'];
            $f_type->quantity = $post['quantity'];
            $f_type->feeding_id = $feed->id;
            $f_type->save();

                if (strpos($post['feeding_type'], 'comm'))
                {
                    foreach ($post['commercial_brands'] as $brand)
                    {
                        $comm_food = new Commercial_food_Model;
                        $comm_food->brand = $brand;
                        $comm_food->feeding_type_id = $f_type->id;
                        $comm_food->save();
                    }
                }
hakre
  • 193,403
  • 52
  • 435
  • 836
kenny99
  • 259
  • 6
  • 19
  • In your example, where is $f_type coming from? – David Yell May 13 '10 at 09:06
  • $f_type is an instantiated object (added code above) - this all works fine on php 5.2, so I think i need to find a different way of iterating...i wonder if a simple for loop would do – kenny99 May 13 '10 at 09:12

1 Answers1

0

Found this in the php documentation comments, it seems to be a bug:

Note that at least in PHP 5.1, objects implementing ArrayAccess cannot return objects by reference. See http://bugs.php.net/bug.php?id=34783 .

If you have code like

<?php
$x = &$y[0];
?>

then this will (as far as I can tell) always fail unless $y is a real array -- it cannot work if $y is an object implementing ArrayAccess. If your offsetGet() function returns by reference, you get the fatal error "Declaration of MyClass::offsetGet() must be compatible with that of ArrayAccess::offsetGet()". If you try to have it return by value, however, you get the (contradictory) fatal error "Objects used as arrays in post/pre increment/decrement must return values by reference", at least in my version of PHP.

It is therefore not possible to take arbitrary code dealing with arrays and try to substitute an object of your own for an array, even if all of the normal array functions didn't fail as well (which they do, or at least some of them).

andsens
  • 6,716
  • 4
  • 30
  • 26