开发者

A strange PHP object

I'm using SimpleXML to get some data from an API. Its returning things in this format:

object(SimpleXMLElement)#10 (1) {
  [0]=>
  string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

My question is, how can I possibly access the string value of this object? If I try to do $myVariable->0 that gives me开发者_运维知识库 an error. Doing $zero = '0' and then echo $myVariable->$zero doesn't work either, nor does (array) $myVariable work (that gives a warning).


The trick is that SimpleXMLElement has __toString magic method implemented that would return your string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", so to get this string you just cast (string) on your SimpleXMLElement object:

(string)$myVariable

With PHP you can

print $myVariable;

of course, so explicit (string) here is not necessarily needed.


AFAIR it's like this:

$myVariable->{0}

Edit: That would work in majority of cases, but not this one. It looks like SimpleXML implements not only __toString method like Nemoden pointed out, but also __get, so that accessing object properties in this way results in cloned object being returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜