如何使用减号访问对象属性? [英] How to access an object property with a minus-sign?

查看:161
本文介绍了如何使用减号访问对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象(在PHP中),我无法打印内容. 在调试模式下,就像这样:

I got an object (in PHP) and I can't print the content. In debug-mode it's like this:

stdClass Object
(
    [pre-selection] => 1
)

但是由于减号,我无法打印预选".

But I can't print the 'pre-selection' because of the minus sign.

echo $object->pre-selection; //doens't work.

如何打印出来?谢谢.

推荐答案

您可以尝试

$object->{'pre-selection'};

http://php. net/manual/en/language.types.string.php#language.types.string.parsing.complex

另请参见 json_decode()

示例#2访问无效的对象属性

Example #2 Accessing invalid object properties

访问对象中包含不包含字符的元素 根据PHP的命名约定(例如,连字符)可以 通过将元素名称封装在花括号和 撇号.

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

更新(感谢萨拉特):

也可以使用大括号,以清楚地界定属性名称.当访问包含数组的属性中的值,属性名称由多个部分组成或属性名称包含无效的字符时,它们最有用

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid

这篇关于如何使用减号访问对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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