Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In php, how similar to an array can I make an object act? And how would I do that?

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.)

like image 270
Kzqai Avatar asked Jan 24 '26 21:01

Kzqai


2 Answers

  • You can make your object Countable so that it works with count
  • You can implement ArrayAccess, so that syntax like $obj['index'] works.
  • Like you've done, you can implement Iterator or IteratorAggregate.

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.
like image 114
Artefacto Avatar answered Jan 27 '26 10:01

Artefacto


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

like image 38
NikiC Avatar answered Jan 27 '26 09:01

NikiC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!