Re: Object to array conversion oddity

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Saturday 23 September 2006 09:40, Marcus Bointon wrote:
> A simple class like this:
>
> class Myclass() {
> public $field1 = '';
> private $field2 = '';
> public function __sleep() {
>    return array('field1', 'field2');
> }
> }
> $myclass = new Myclass;
>
> If I var_dump this, I get:
>
> object(Myclass)#6 (2) {
>    ["field1"]=>
>    string(0) ""
>    ["field2:private"]=>
>    string(0) ""
> }
>
> If I coerce this to an array:
>
> $arr = (array)$myclass;
>
> the properties change names in a most unhelpful way:
>
> array(2) {
>    ["field1"]=>
>    string(0) ""
>    ["Myclassfield2"]=>
>    string(0) ""
> }
>
> The docs (http://www.php.net/manual/en/language.types.array.php) say:
>
> "If you convert an object to an array, you get the properties (member
> variables) of that object as the array's elements. The keys are the
> member variable names."
>
> It seems that's not quite true.
>
> How can I stop it doing this? Looks a bit buggy to me.
>
> Marcus
> --
> Marcus Bointon
> Synchromedia Limited: Creators of http://www.smartmessages.net/
> marcus@xxxxxxxxxxxxxxxxxx | http://www.synchromedia.co.uk/

To me it looks like they append the name of the class to any private 
variables.  I would guess that it does this to make sure you know what you're 
doing and using the private variable like that.  I'm  just guessing at that 
point though.

Try a test with multiple public and multiple private variables.  If the format 
of the array keys stays the same, then you should have your answer.

HTH

-- 
Ray Hauge
Programmer/Systems Administrator
American Student Loan Services
www.americanstudentloan.com
1.800.575.1099

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux