0

I want to reference an attribute in a object dynamically, as not all of my objects have the same attributes, like:

if ($person->$status) {
    //do this
}

Person is a stdClass Object:

stdClass Object
                    (
                        [name] => name
                        [silver] => 214321
                        [gold] => 334532
                    )

the variable $status in my example above could be the string value "silver" or "gold" or any other value and I want to check whether the object has an attribute with that value or not.

The example above is not exactly my case, I just created it to demonstrate my problem.

Thank you!

0

2 Answers 2

1

You can use the property_exists method to check whether a property is present in the object:

if(property_exists($person, $status)) {
  // Do something
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use get_object_vars to get an array of the object's accessible properties:

$person_array = get_object_vars($person_object);
if ($person_array[$status]) {
    // do this
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.