views:

214

answers:

3

I have a PHP Object which contains other objects

i.e

$obj->sec_obj->some_var;

I want to use a foreach loop to loop through the object and all objects objects. I think the max level is 3, so

$obj->sec_obj->third_obj->fourth_obj

Any ideas?

+3  A: 

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";
    }
}
Reinis I.
How can i use this to print the key and value?
dotty
See my edit. --
Reinis I.
thanks you man.
dotty
A: 

Check out this page: http://www.php.net/manual/en/language.oop5.iterations.php

You can use foreach to loop though the public members of an object, so you could do that with a recursive function.

If you want to be a bit more fancy, you could use an Iterator.

therefromhere
A: 

Use a recursive function. A function that calls it's self if the value passed in is an object not the value you're looking for. Careful not to get into an infinite loop though!

here is a good article.

http://devzone.zend.com/article/1235

Joel