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 foreach
ed 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.)
- 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
.
Have a look at the ArrayAccess
and Countable
interfaces. The former allows accessing your object using $obj[...]
, the latter allows count($obj);
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.
精彩评论