|
|
|
|
Re: ArrayAccess interface, Traversable interface and foreach [message #185991 is a reply to message #185990] |
Sat, 24 May 2014 08:37   |
|
Jerry Stuckle wrote:
> On 5/24/2014 6:05 AM, Christoph Michael Becker wrote:
>> kurtk(at)pobox(dot)com wrote:
>>
>>> The documentation for ArrayAccess (at
>>> http://www.php.net/manual/en/class.arrayaccess.php) doesn't show it
>>> implementing Traversable. Nevertheless, you can still use any class
>>> you write that implements ArrayAccess in a foreach loop.
>>>
>>> This seems like an oversight in the documentation--unless I am
>>> missing something?
>>
>> You can use any object (whether it is an instance of a class that
>> implements Traversable or not) in a foreach loop, see
>> <http://www.php.net/manual/en/control-structures.foreach.php>.
>>
>
> But that is an entirely different access to what Kurt is talking about.
>
> Kurt is discussing how to transverse an array within an object; your
> page discusses how to transverse public data members in an object. But
> good OO practices says all data members should be private.
To traverse an array which is a member of an object $o with foreach($o
....), the object's class has to implement IteratorAggregate or Iterator,
not ArrayAccess.
--
Christoph M. Becker
|
|
|
Re: ArrayAccess interface, Traversable interface and foreach [message #185996 is a reply to message #185989] |
Tue, 27 May 2014 14:59   |
|
On Sat, 24 May 2014 12:05:02 +0200, Christoph Michael Becker wrote:
> kurtk(at)pobox(dot)com wrote:
>
>> This seems like an oversight in the documentation--unless I am missing
>> something?
>
> You can use any object (whether it is an instance of a class that
> implements Traversable or not) in a foreach loop, see
> <http://www.php.net/manual/en/control-structures.foreach.php>.
Yep, this is why objects that implement ArrayAccess still work with
foreach without implementing Traversable.
ArrayAccess and Traversable are technically different things: Traversable
provides a way to control iteration, whereas ArrayAccess is only for
array-style dereferencing via $object['key']. In practice, classes that
need to imitate arrays will need to implement both (probably by extending
a class such as ArrayObject that implements both interfaces).
Adam
|
|
|
|