一個對象,怎麼又同時是數組?

來源:互聯網
上載者:User
simpleXML中,將xml檔案轉成了一個對象,根節點就是這個對象,訪問子節點就是對象的成員屬性。有下面這個xml文檔:

如何成功?張三39.8成功人士應該有的特質李四42.8


$xml_obj=simplexml_load_file("books.xml"); $books=$xml_obj->book;$book=$books[0]; //這是第一本書,他是一個對象,他下面的子節點可以通過訪問他的成員方法擷取,但是他的屬性,,,,,,$lang=$book["lang"];//擷取他的屬性,lang。以數組的方式訪問,但是他不是一個對象嗎?


我不明白的地方是這樣的,訪問節點屬性的時候是以數組的方式去訪問的,但是$book是一個對象啊!怎麼變成數組了?


回複討論(解決方案)

http://www.php.net/manual/zh/class.arrayaccess.php

[book] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[lang] => 中文
)

[name] => 如何成功?
[author] => 張三
[price] => 39.8
)

摘錄手冊一段,留意紅色部分:
-------------------------------------------------------
The SimpleXMLElement class
(No version information available, might only be in SVN)
簡介
Represents an element in an XML document.
類摘要
SimpleXMLElement implements Traversable {
……
-----------------------------------------------------------------

Traversable 是SPL的一個類(目前手冊並無具體介紹,但去 php.net 能發掘到)
再摘錄一小段給你

-----------------------------------------------------------------------------

Traversable Interface Reference
[Zend engine classes]
Interface to detect a class is traversable using foreach. More...

Detailed Description
Interface to detect a class is traversable using foreach. //這就意味著是可迭代對象

Since:
PHP 5.0
Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.

Note:
Internal classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
This is an engine internal interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.


Definition at line 509 of file spl.php.


--------------------------------------------------------------------------------
The documentation for this interface was generated from the following file:
spl.php

[book] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[lang] => 中文
)

[name] => 如何成功?
[author] => 張三
[price] => 39.8
)


[@attributes] => Array


這裡的@是什麼意思啊?我對正宗的數組var_dump沒有出現這個@符號。

SimpleXMLElement 對象的屬性數組
一般用遍曆 attributes 方法返回的數組進行操作
你那樣寫也是可以的

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.