note 69872 added to language.types.array
| From: | marcus at synchromedia dot co dot uk | Date: | Sun, 24 Sep 2006 21:42:31 +0000 |
| Subject: | note 69872 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-117540@lists.php.net to get a copy of this message | ||
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).
----
Server IP: 83.138.144.80
Probable Submitter: 87.74.30.27
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/69872
Del: integrated -- https://master.php.net/note/delete/69872/integrated
Del: useless -- https://master.php.net/note/delete/69872/useless
Del: bad code -- https://master.php.net/note/delete/69872/bad+code
Del: spam -- https://master.php.net/note/delete/69872/spam
Del: non-english -- https://master.php.net/note/delete/69872/non-english
Del: in docs -- https://master.php.net/note/delete/69872/in+docs
Del: other reasons-- https://master.php.net/note/delete/69872
Reject -- https://master.php.net/note/reject/69872
Search -- https://master.php.net/manage/user-notes.php