Cast object to array - strange behaviour [duplicate]

廉价感情. 提交于 2019-12-31 02:59:08

问题


I am casting an object to array and after that I am unable to access the resulting array by a key.

This is the code

print_r($new);
$new = (array)$new;
echo $new['EPPContactemail'];

foreach($new as $attr=>$value)
{
    echo "$attr => $value \n";
}

And the output is

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

I can clearly see that EPPContactemail key exists and holds the value although when accessing it (line 3, echo statement) it throws an error of undefined index.

Could you please explain me what causes this behaviour?


回答1:


When casting an object to an array, certain properties (private, protected and parent properties) are assigned to the array, with keys that look like:

*protected
ClassNamePrivate
ParentNameProperty

But they really look like this:

"\0*\0protected"
"\0ClassName\0Private"
"\0ParentName\0Property"

That's what's causing your problems here.
Replace:

echo $new['EPPContactemail'];

with

echo $new["\0EPPContact\0email"];

And take it from there.
Note that you'll have to use double quotes as string delemiters, because '\0' !== "\0", just as '\n' !== "\n"

This behaviour is documented on php.net, though it's rather well hidden



来源:https://stackoverflow.com/questions/17695490/cast-object-to-array-strange-behaviour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!