note 69872 rejected from language.types.array by bjori
| From: | bjori@php.net | Date: | Mon, 25 Sep 2006 08:17:01 +0000 |
| Subject: | note 69872 rejected from language.types.array by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117617@lists.php.net to get a copy of this message | ||
Note Submitter: marcus at synchromedia dot co dot uk
----
The docs above say this about casting to array (e.g. (array)$myobject):
"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."
This is not quite true. It is true of public properties, but that's all. Private properties are
renamed to NULL<classname>NULL<propertyname>, and private properties in superclasses ARE
included in the result (which is odd since they are completely invisible to the object). Protected
properties are renamed to NULL*NULL<propertyname>.
This function does the conversion exactly as the documentation says (though it will not preserve
references in PHP4), and does not include private properties of superclasses, that is, the number of
results will exactly match the number of properties visible within the class.
/**
* 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 does (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]*)$/i', $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;
}
(remove the line breaks inside the regular expressions).