Re: is_array on objects with ArrayAccess or Iterator implementations
| From: | Etienne Kneuss | Date: | Tue, 29 Dec 2009 02:01:23 +0000 |
| Subject: | Re: is_array on objects with ArrayAccess or Iterator implementations | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-46566@lists.php.net to get a copy of this message | ||
Hi,
On Tue, Dec 29, 2009 at 1:27 AM, Clint Priest <cpriest@warpmail.net> wrote:
> Etienne Kneuss wrote:
>>
>> On Tue, Dec 29, 2009 at 12:04 AM, Clint Priest <cpriest@warpmail.net>
>> wrote:
>>>
>>> Unfortunately $x instanceOf ArrayAccess doesn't return true when $x is
>>> indeed an array.
>>
>> Making is_array return true for objects implementing ArrayAccess is a
>> bad idea, for two main reasons:
>>
>> 1) is_array is a type check, and we should still be able to
>> distinguish real arrays from objects
>
> That's true of course, definitely would need to be able to distinguish.
>
>> 2) ArrayAccess does not guarantee that an object will behave like an
>> array, (e.g. you won't be able to use sort() on an object implementing
>> ArrayAccess.
>
> I wonder if this is something that users would be expecting, that any
> function which took an array would also take an object that implements
> certain interfaces (such as ArrayAccess and perhaps Countable).
>
>> If, in your case, you want to accept both arrays and ArrayAccess
>> objects, I guess if (is_array($v) || $v instanceof ArrayAccess) is a
>> sufficiently good way to check.
>>
>
> I'm finding myself implementing ArrayAccess more and more often because its
> so transparent to the consumer. The reason this came up is because I was
> considering returning all arrays from a certain section of my shared code
> library always be an array object so that things like
> $tblArray->pluck('Value') could be done, rather than array_pluck() type
> functionality.
>
> That got me to thinking about all of the is_array() calls I would need to
> replace throughout the codebase.
>
> Would it be terribly difficult to make objects with ArrayAccess completely
> interchangable anywhere an array element would be required by a function?
Yes, definitely, it would be a quite big amount of work (basically
rewriting every functions dealing with arrays), and the interface that
ArrayAccess proposes isn't enough for most array tasks.
>
--
Etienne Kneuss
http://www.colder.ch