Loop through object containing php object
I have a PHP object that contains other objects
i.e
$obj->sec_obj->some_var;
I want to use a foreach loop to loop through the object and objects of all objects. I think the max level is 3, so
$obj->sec_obj->third_obj->fourth_obj
Any ideas?
It's just basic recursion.
function loop($obj)
{
if (is_object($obj)) {
foreach ($obj as $x) {
loop($x);
}
} else {
// do something
}
}
Edit : printing key and value pairs:
function loop($obj, $key = null)
{
if (is_object($obj)) {
foreach ($obj as $x => $value) {
loop($value, $x);
}
} else {
echo "Key: $key, value: $obj";
}
}
Have a look at this page: http://www.php.net/manual/en/language.oop5.iterations.php
You can use foreach
to loop if the public members of the object, so you can do it with a recursive function.
If you want to be a little more quirky, you can use an Iterator.
Use a recursive function. The function that calls this itself if the value passed to is an object and not the value you are looking for. Be careful not to end up in an endless loop!
here is a good article.
http://devzone.zend.com/article/1235