Re: [RFC] Iterable

From: Date: Sat, 02 Jul 2016 14:39:26 +0000
Subject: Re: [RFC] Iterable
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-94361@lists.php.net to get a copy of this message
Hi Jeremy, > On Jun 30, 2016, at 3:01 PM, Jeremy Mikola <jmikola@gmail.com> wrote: > > Was there any discussion about a special allowance being made for stdClass? > > I've noted the is_iterable(new stdClass) example and ensuing "Object Iteration" > section: > > PHP allows any object to be used with foreach. However, iterable does not accept any object, > only those implementing Traversable. Values accepted by iterable should be designed for iteration, > not any set of values (such as the public properties of an object or a string). > > I'm on the fence if that second sentence applies to stdClass. Based on how users typically > end up with stdClass instances (e.g. casting arrays to an object, json_decode()), I tend to think of > them as logically equivalent to associative arrays. To that end, I'd consider stdClass to be as > "designed for iteration" as any associative array -- if we can even say a stdClass was > designed at all :) > > As-is, the RFC requires users to either cast stdClass instances to an array or decorate them > with an Iterator (e.g. ArrayObject). I find this a bit irksome, but it's certainly easy to work > around. > > That said, I realize that voting is in progress and it's not my intention to interrupt > anything. I just wanted to relay a viewpoint that might not have come up. > Generally when I've seen an object that did not implement Traversable used with foreach it has been an error. The exception of course is stdClass, particularly because of json_decode(). There was no discussion on the list of allowing stdClass, but I did discuss it with some people in chat. Our consensus was that a casting to an array was a reasonable and simple requirement to allow an instance of stdClass to be iterable. I do not think stdClass was designed for iteration, but rather is just used this way because of the behavior of foreach. I'd prefer json_decode() to return an iterable object... maybe an RFC for another day. Aaron Piotrowski

« previous php.internals (#94361) next »