如何在 PHP 对象的名称中使用 @ 符号
我有一个 XML 文件,其中的标签 @attributes 代表
SimpleXMLElement Object
(
[@attributes] => Array
(
[PART_NUMBER] => ABC123
我想要引用此对象的名称之一,例如 $product->@attributes['part_number'] 但 @ 符号当然会导致错误。
那么如何在对象中引用此项呢?
I've got an XML file that has the label @attributes for one of the names
SimpleXMLElement Object
(
[@attributes] => Array
(
[PART_NUMBER] => ABC123
I want to make a reference to this object like $product->@attributes['part_number'] but of course the @ symbol causes an error.
So how do I reference this item in the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,对于 SimpleXML,您可以调用 手册。这将为您提供一个将属性名称映射到值的数组。
Well, in the case of SimpleXML, you'd call the
$product->attributes()
method as defined in the manual. That will give you an array mapping attribute names to values.$obj
:访问
@id
和$
:$obj
:To access
@id
and$
:$product[0]['PART_NUMBER']
应该可以。如果您有多个属性,则应在
foreach
中使用$product->attributes()
SimpleXML 手册中的属性
$product[0]['PART_NUMBER']
should work.If you got more than one attribute, you should use
$product->attributes()
in aforeach
attributes in SimpleXML manual
如果您使用的是 SimpleXML 对象,则已经内置了一个
attributes
方法(不带@
符号)——像这样使用它:$product- >attributes('part_number');
如果您尝试创建自己的对象来映射到 XML,那么正如您已经发现的,您不能使用
@
PHP 变量名中的符号(也不是除下划线之外的任何其他符号)。我建议简单地使用
$product->attributes['part_number']
(即根本没有@
符号)并将其映射到您的类中。如果您确实需要将其映射到变量名称中,那么您真正希望的最好的结果就是某种替换字符串,您可以在两种格式之间进行转换时换入和换出该字符串。
例如:
$product->at__attributes['part_number']
但这并不是一个特别好的解决方案,恕我直言。
If you're using SimpleXML objects, is already have an
attributes
method built into it (without the@
sign) -- use it like this:$product->attributes('part_number');
If you're trying to create your own objects to map to the XML, then as you already found out, you can't use the
@
symbol in a PHP variable name (nor any other symbol except underscore).I'd suggest simply using
$product->attributes['part_number']
(ie without the@
symbol at all) and mapping it inside your class.If you really need to map it into your variable names, the best you can really hope for would be some kind of replacement string that you can swap in and out as you convert between the two formats.
eg:
$product->at__attributes['part_number']
But that's not really a particularly good solution, IMHO.