【发布时间】:2016-12-25 15:10:02
【问题描述】:
当我做这样的事情时,我正在运行 PHP7.0.9:
$s = json_decode('{"1": "xxx"}');//decode json to stdClass
$a = (array)$s;//cast to array
die(var_dump($a, $a['1'], $a[1], count($a)));
我得到这个结果:
array (size=1)
'1' => string 'xxx' (length=3) //<-- key 1 exists
null // $a['1'] yields null
null // $a[1] doesn't work either
int 1 // count shows there is 1 element in the array
我期待这个结果:
array (size=1)
'1' => string 'xxx' (length=3)
string 'xxx' (length=3) // $a['1'] should work
null
int 1
我的问题:为什么我不能访问$a['1'],即使数组的count 和var_dump 都告诉我这个密钥存在?这是 PHP 中的错误,还是某种功能?
【问题讨论】:
-
我在 PHP 5 中得到了相同的结果。
-
@Rizier123 但他访问的是数组,而不是对象。
-
对象属性必须以
A-Za-z或underscore开头,并且不应以数字或仅以数字开头!您的代码强制执行的任何行为都是未知的。 -
@JustOnUnderMillions 这不是真的。您可以拥有其他对象属性,您只需使用更复杂的语法来访问它们。
-
保存在保存区。取消保存区域
$r=new stdClass(); $r->²³='A'; print $r->²³;