Re: Object to array conversion oddity
| From: | Marcus Bointon | Date: | Sat, 23 Sep 2006 21:35:30 +0000 |
| Subject: | Re: Object to array conversion oddity | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-242160@lists.php.net to get a copy of this message | ||
I've written a function that does a conversion that matches the docs, based on the other info I've mentioned:
/**
* Clean up the name munging that PHP applies while casting from object to array
* The resulting array looks like what the documentation says that (array)$object delivers, but actually doesn't
* @param object $object The object to convert
* @return array
*/
function object2array($object) {
$class = get_class($object);
$array = (array)$object;
$propArray = array();
$matches = array();
foreach ($array as $key => $value) {
if (preg_match('/^\0(([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\0([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$/', $key, $matches)) {
//It's a private property
if ($matches[1] == $class) { //Ignore private props of superclasses
$propArray[$matches[2]] = $value;
}
} elseif (preg_match('/^\0(\*)\0([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$/', $key, $matches)) {
//It's a protected property
$propArray[$matches[2]] = $value;
} else {
//It's a public property
$propArray[$key] = $value;
}
}
return $propArray;
}
Works nicely for me.
Marcus
--
Marcus Bointon
Synchromedia Limited: Creators of http://www.smartmessages.net/
marcus@synchromedia.co.uk | http://www.synchromedia.co.uk/