note 84260 added to function.get-object-vars
| From: | jon at websandbox dot net | Date: | Sun, 06 Jul 2008 04:00:07 +0000 |
| Subject: | note 84260 added to function.get-object-vars | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-141212@lists.php.net to get a copy of this message | ||
If you're using the SPL ArrayObject class (or similar, or the ArrayAccess interface), you may
have noticed that it's difficult to loop through an object's properties.
get_object_vars does not return the properties of an ArrayObject. The only workaround I can see is
to use get_class_vars.
<?php
$obj = new ArrayObject();
$obj->foo = "bar";
$obj[] = "1";
$obj[] = "2";
foreach($obj as $key => $value) {
// will iterate over the array, iterating over "1" and "2", but ignoring
$obj->foo
}
var_dump($obj); // dumps the array values, ignores $obj->foo
$a = get_object_vars($obj); // returns an empty array
class Fart extends ArrayObject {
public $foo = "bar";
}
$obj = new Fart();
$a = get_object_vars($obj); // return an empty array
$a = get_class_vars(get_class($obj)); // returns array("foo"=>"bar"), Yay!
/* The above works with subclasses as well */
class Toot extends Fart {
public $weeble = "wobble";
}
$a = get_class_vars(get_class($obj));
// returns array("weeble" => "wobble", "foo"=>"bar"),
Yay again!
?>
So, to iterate over the properties of an ArrayObject, and not the array values:
<?php
$obj = new Toot(); // which is a subclass of ArrayObject
$props = get_class_vars(get_class($obj));
foreach($props as $prop => $defaultValue) {
$value = $obj->$prop; // now you have the property name and its value
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 70.128.47.139
----
Manual Page -- http://www.php.net/manual/en/function.get-object-vars.php
Edit -- https://master.php.net/note/edit/84260
Del: integrated -- https://master.php.net/note/delete/84260/integrated
Del: useless -- https://master.php.net/note/delete/84260/useless
Del: bad code -- https://master.php.net/note/delete/84260/bad+code
Del: spam -- https://master.php.net/note/delete/84260/spam
Del: non-english -- https://master.php.net/note/delete/84260/non-english
Del: in docs -- https://master.php.net/note/delete/84260/in+docs
Del: other reasons-- https://master.php.net/note/delete/84260
Reject -- https://master.php.net/note/reject/84260
Search -- https://master.php.net/manage/user-notes.php