views:

56

answers:

3

I know that by implementing iterable you can make an object able to be foreached over. I'd like to take it further and make an object react like an array would in as many places as possible where an array is called for.

(The reason for this is because I'm selecting data from a database, and the statement object that results by default is very good on memory, whereas the full dataset in array form tends to throw the memory usage into orbit. I'd love to have the best of both worlds, array type usage with the lower memory usage up until the moment that an array type of behavior is called for.)

+1  A: 

Don't know if this is what you need, but you can:

// $your_object

foreach(get_object_vars($your_object) as $property=>$value) /* do something */ ;

If memory serves me right, you can (interchangeably) use typecasting wherever you need.

Perhaps it's not considered OOP candy, but it's imperative stuff that works.

Christian Sciberras
+6  A: 

What you can't do:

You can't make it work with the array functions, except these, which kind of work, but rely on converting the object to an array, which is done by fetching its properties:

  • end, prev, next, reset, current, key
  • array_walk, array_walk_recursive, array_key_exists.
Artefacto
Thanks for that breakdown, I'm going to see what I can do with that, though I realized my problem is slightly deeper/more complicated, so I'm going to rephrase a question with that deeper problem in mind. (I realized that my problem is that the database statement object will not react like an array when an array is what is, though perhaps I can simply wrap the statement object in a more appropriate kind of object implementing the things above).
Tchalvak
***will not act like an array even when an array is needed
Tchalvak
Ah, and it seems like the ArrayAccess interface is a solution to that issue.
Tchalvak
+2  A: 

Have a look at the ArrayAccess and Countable interfaces. The former allows accessing your object using $obj[...], the latter allows count($obj);

nikic