0

Is there any similar PHP function that can unserialize to an object instead of always to an array?

$session_data = unserialize($tmp[0]); // I need this to be an object

I need to unserialize to an object so I can access values like $session_data->FirstName instead of $session_data['FirstName'].

EDIT: I have a function that will do this, but to me it seems sloppy and I was wondering if there was a way of doing this natively within PHP:

function ato($array) {
    $obj= new stdClass();
    foreach ($array as $k=> $v) {
        if (is_array($v)) {
            $v = array_to_object($v);
        }
        $obj->{strtolower($k)} = $v;
    }
    return $obj;
}
MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • 2
    Yes read the `serialize()` documentation. If you serialize an object you can use the data to unserialize the same object – RiggsFolly Aug 13 '15 at 23:06
  • This has been answered in full here: Can you create instance properties dynamically in PHP? Short summary. You can either use a class constructor method to dynamically generate properties with an associative array or you can use magic methods to customize your setter and getter methods to do the same on a name-by-name basis. – sunny Aug 13 '15 at 23:11

1 Answers1

1

Here you go:

$foo = [
    'bar'  => 'baz',
];
$foo = (object)$foo;
echo $foo->bar;
baao
  • 71,625
  • 17
  • 143
  • 203