PHP array in object to string conversion (as far as I can tell)

I am developing front-end code for a web application and am facing an odd number of problems with a custom object. When I ask for an object and use print_r()

it I get this (the object is much larger, just slice it up into the appropriate code):

MemberInfo Object
(
    [meta_data] => Array
    (
        [email_recommendations] => true
        [email_updates] => false
    )
)

      

To change something in the MemberInfo object, I just update its properties and post it back to the backend with a second function. So, for example, the page is loaded once (which gives us the object shown above), then I send a POST request with the changes on the second page load. On the second load, I take the object above, set one field differently based on POST with something like $memberInfo->meta_data['email_recommendations'] = 'false';

, and then use that version of the object to populate the page after running the refresh function (something like updateMember($memberInfo);

). However, as soon as I change the value of the property of the object, it print_r()

shows me something different:

MemberInfo Object
(
    [meta_data] => {\"email_recommendations\":\"false\",\"email_updates\":\"false\"}

)

      

I'm sure I'm missing something very silly; does anyone have a good idea of ​​what i should be looking for? I have checked and the backend code is not passed by reference (function call updateMember(MemberInfo $memberInfo);

), but I'm a bit wobbly at handling PHP 5 objects so I'm not sure what might be going wrong.

I don't expect deep debugging; I just need to know the general direction in which I should be looking for what is causing this change in a property, which by all rights should be an array.

Thanks in advance!

0


source to share


1 answer


so are you using the object after the call updateMember()

? PHP5 objects are passed by reference by default, so if you call json_encode()

on a property meta_data

it will exhibit the behavior you described.

you can send a function updateMember()

to confirm, but it looks like what is happening.



t

class MemberInfo {
    function __construct()  {
        $this->meta_data = array(
            'email_recommendations' => true,
            'email_updates' => false,
        );
    } 
}

function updateMember($meminfo) {
    $meminfo->meta_data = json_encode($meminfo->meta_data);
    // do stuff
}

$meminfo = new MemberInfo();

updateMember($meminfo);

print_r($meminfo); // you'll see the json encoded value for "meta_data"

      

+1


source







All Articles