我正在将一个对象转换为数组,然后我无法通过一个键访问生成的数组。
这是代码
print_r($new);
$new = (array)$new;
echo $new['EPPContactemail'];
foreach($new as $attr=>$value)
{
echo "$attr => $value \n";
}
输出
EPPContact Object
(
[id:EPPContact:private] => 6553377C74FC9899
[roid:EPPContact:private] => 50085436-UK
[status:EPPContact:private] => ok
[voice:EPPContact:private] => +44.554545454
[email:EPPContact:private] => some@email.com
[fax:EPPContact:private] =>
[clID:EPPContact:private] => TSOHOST
[crID:EPPContact:private] => EPP-TSOHOST
[crDate:EPPContact:private] => 2013-07-17T09:53:41
)
Notice: Undefined index: EPPContactemail in /home/parvhraban/domains/src/local_libs/EPP/Builder/Contact/Update.php on line 9
EPPContactid => 6553377C74FC9899
EPPContactroid => 50085436-UK
EPPContactstatus => ok
EPPContactvoice => +44.554545454
EPPContactemail => some@email.com
EPPContactfax =>
EPPContactclID => TSOHOST
EPPContactcrID => EPP-TSOHOST
EPPContactcrDate => 2013-07-17T09:53:41
我可以清楚地看到EPPContactemail密钥存在并保存该值,但在访问它时(第3行,echo语句)它会抛出未定义索引的错误。
请您解释一下导致这种行为的原因是什么?
答案 0 :(得分:8)
将对象强制转换为数组时,会将某些属性(private,protected和parent属性)分配给数组,其中的键看起来像:
*protected
ClassNamePrivate
ParentNameProperty
但他们看起来真的像这样:
"\0*\0protected"
"\0ClassName\0Private"
"\0ParentName\0Property"
这就是造成你问题的原因 替换:
echo $new['EPPContactemail'];
带
echo $new["\0EPPContact\0email"];
从那里拿走它
请注意,您必须使用双引号作为字符串删除者,因为'\0' !== "\0"
,就像'\n' !== "\n"
此行为记录在php.net上,though it's rather well hidden