views:

42

answers:

2

I really am clueless when it comes to object-oriented programmings, so forgive me if this is obvious...

I am using a Zend extension which returns a request as a nested object. I need property a based on if the object has property b. Right now I am using a foreach loop with a conditional to search for property b and, if I get a match, set my variable to property a.

Something like:

 foreach($nested_object as $object) {
    if($object -> foo -> bar == "match") {
         $info = $object -> stuff -> junk;
    }
 }

I was hoping there was a more elegant way to do this, along the lines of XPath (but certainly it doesn't have to be remotely close to XPath, just something as simple).

So if I know the property I need, is there a way in PHP to retrieve any and all objects with that property?

+1  A: 

There is no built in automatic way to do that. The closest OOP way is to add a method to the collection class (your nested object) which will do the search and return the proper object(s). That method would look a lot like your code. If you don't need to do this more than one place, then you're doing it the 'right' way (for now) in my opinion.

Scott Saunders
Thanks! I was afraid that was the answer, but I'm glad I didn't just blindly miss something in the documentation. Upvote for now, I'll mark this the answer sometime today unless someone out there can show the opposite is true.
Anthony
A: 

You can always simply peform a isset() check on property b

if (isset($object->b)) {
    $info = $object->a;
}

To make an assumption, since you are using Zend it might be something like this

if (isset($this->request)) {
    $info = $this->request;
}
nwhiting
The property will exist in all instances of the sub-object (as far as I know). The trick is knowing if the property value matches what I need.
Anthony