我得到了一个对象(在PHP中),但我无法打印内容。在调试模式下,它是这样的:
stdClass Object
(
[pre-selection] => 1
)
但是由于减号的存在,我无法打印“预选”。
echo $object->pre-selection; //doens't work.
我该如何打印这个?谢谢。
我得到了一个对象(在PHP中),但我无法打印内容。在调试模式下,它是这样的:
stdClass Object
(
[pre-selection] => 1
)
echo $object->pre-selection; //doens't work.
$object->{'pre-selection'};
http://php.net/manual/zh/language.types.string.php#language.types.string.parsing.complex
另请参阅json_decode()
的示例2。
示例#2 访问无效的对象属性
访问对象内包含违反 PHP 命名约定的字符(例如连字符)的元素,可以通过将元素名称用大括号和单引号括起来来实现。
<?php $json = '{"foo-bar": 12345}'; $obj = json_decode($json); print $obj->{'foo-bar'}; // 12345 ?>
更新(感谢salathe):
花括号也可以用于清晰地界定属性名称。当访问包含数组的属性内部值时,当属性名称由多个部分组成或属性名称包含其他无效字符时,它们最为有用。
有多种方法,问题在于PHP分词器会在代码中的-
符号处出现故障,但您可以编写代码以使解析器不会发出投诉:
echo $object->{'pre-selection'};
或者
$property = 'pre-selection'
echo $object->$property;
或者
$array = (array) $object;
echo $array['pre-selection'];
Accessing elements within an XML document 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.
Example #3 Getting <line>
<?php include 'example.php'; $movies = new SimpleXMLElement($xmlstr); echo $movies->movie->{'great-lines'}->line; ?>
The above example will output:
PHP solves all my web problems