如何简单的XML使用[]运算符? [英] How does Simple XML use the [] operator?

查看:1286
本文介绍了如何简单的XML使用[]运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中您可以使用一个元素的方括号访问属性:

In PHP you can use square brackets on an element to access attributes:

$node = /* SimpleXMLElement */
$id = $node['id'];

什么是奇怪的是,的$ id 不是一个字符串,它的另一个的SimpleXMLElement 。为什么不是一个字符串?我发现自己使用 strval()遍布在这个地方。

What's weird is that $id isn't a string, It's another SimpleXMLElement. Why isn't it a string? I find myself using strval() all over the place on this.

如何在方括号的工作?我能做到这一点我自己的课?我还没有看到在这个文档中任何事情这一点。

How are the square brackets working? Can I do that with my own classes? I Haven't seen anything in the docs about this.

推荐答案

您可以提供像数组通过实施的了ArrayAccess接口,这是PHP的标准库的一部分。这个接口是那些即使你没有安装完整的PHP标准库扩展呢,你还可以有这个接口在PHP 5的事情之一。

You can provide Array like access to your object by implementing the ArrayAccess interface, which is part of the PHP Standard Library. This interface is one of those "even if you don't have the full PHP Standard Library extension installed, you still have this interface available in PHP 5" things.

通过实现这个接口,并定义你的类四种方法

By implementing this interface, and defining four methods for your class

public boolean offsetExists  ( string $offset  )
public mixed offsetGet ( string $offset )
public void offsetSet ( string $offset , string $value )
public void offsetUnset ( string $offset )

您应该能够使用方括号与实例化的对象。

you should be able to use square brackets with your instantiated objects.

至于SimpleXML的本身,我不知道,如果它真正实现了ArrayAccess接口,或者如果有别的事情在给它这些超能力的PHP源幕后。

As for SimpleXML itself, I'm not sure if it actually implements the ArrayAccess interface, or if there's something else going on behind the scenes in the PHP source that gives it these super powers.

这篇关于如何简单的XML使用[]运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆