Re: When is an array not an array?
- From: Andy Hassall <andy@xxxxxxxxxxx>
- Date: Mon, 30 Oct 2006 14:36:20 +0000
On Mon, 30 Oct 2006 14:24:45 GMT, "Andrew C" <nonsense@xxxxxxxxxxxxxxx> wrote:
I've encountered what seems to me to be something of an oddity while playing
around with XML parsing in PHP, and I wondered if any of you might be able
to clear up my confusion...
Here's a little code:
$xmlDoc = new DOMDocument();
$xmlDoc->load('widget_data.xml');
$widgets = $xmlDoc->getElementsByTagName('widget');
My understanding was that '$widgets' is an array of elements,
Nope - it's a DOMNodeList object, that has support for PHP5 iterators, so you
can use it in a foreach loop.
and the
following 'foreach' iterates through that array (this works):
foreach ($widgets as $widget)
{
...
}
However, I get an error if I try to access '$widgets' using square-brackets,
e.g.:
$widget = $widgets[0];
(The error is: "Fatal error: Cannot use object of type DOMNodeList as
array".)
There you go.
PHP confirms that the first element of the 'array' has an index/key of '0'
with the following (or similar), but won't let me access it directly using
'$widgets[0]':
foreach ($widgets as $key => $widget)
{
echo("<p>" . $key . "</p>\n");
}
Does anyone have an explanation as to why a DOMNodeList can be accessed like
an array using 'foreach', but won't allow square-brackets to be used? What
exactly *is* a DOMNodeList?
Thanks for any help.
A.
PS. I am aware that DOMNodeLists have an 'item()' method with which nodes
within the list can be referred to via index, but my confusion still stands
as to why I can't simply use '[]'s.
PHP doesn't support overloading operators, which I believe would be required
for supporting [] on objects implementing the appropriate interface.
Would be a sensible extension to the current functionality, though - as you
point out, DOMNodeList acts almost the same as an array, but not quite close
enough.
Failing that, it'd be somewhat useful if DOMNodeList had a method to convert
itself into an actual array, but it doesn't seem to have that either.
--
Andy Hassall :: andy@xxxxxxxxxxx :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
.
- Follow-Ups:
- Re: When is an array not an array?
- From: Andrew C
- Re: When is an array not an array?
- From: PleegWat
- Re: When is an array not an array?
- From: whiskey
- Re: When is an array not an array?
- References:
- When is an array not an array?
- From: Andrew C
- When is an array not an array?
- Prev by Date: When is an array not an array?
- Next by Date: Re: Create thumbnails with clickable links XYZ
- Previous by thread: When is an array not an array?
- Next by thread: Re: When is an array not an array?
- Index(es):
Relevant Pages
|