문제

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!

도움이 되었습니까?

해결책

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

if(property_exists($person, $status)) {
  // Do something
}

다른 팁

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
} 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top