在SimpleXMLElement对象中误用方括号

时间:2010-07-16 02:11:08

标签: php xml

我发现,当再次使用SimpleXMLElement对象时,[]运算符有时会让人感到困惑。

$level_a = $xml->children();
$level_a['name'];    # this returns the 'name' attribute of level_a (SimpleXmlElement object)
$level_a[0];         # this returns $level_a itself!
$level_a[1];         # this returns the second SimpleXmlElement object under root node. (Same level as level_a)

我找不到任何有关SimpleXmlElement类的数字索引用法的文档。任何人都可以解释这两个是如何工作的吗?

请注意,SimpleXmlElement的[num]运算符似乎只是模仿Array的行为。我觉得这不是用Array激发的东西,而是SimpleXmlElement类的实现。

1 个答案:

答案 0 :(得分:1)

我不相信任何神奇的东西在这里发生。 PHP中的数组可以用整数键控,也可以用字符串键控。因此$xml->children()行可能会以

形式创建一组键值属性对
foreach (attrs($element) as $attribute_name => $attribute_value)
    $array[$attribute_name] = $attribute_value;
$array[0] = $element;
// etc.