PHP: Accessing an object property with a variable.
- by Peter
Let's assume I have an array of object properties I'd like to access:
$properties = array('foo', 'bar');
I'd like to loop through the object and access these properties dynamically (specifically, I'm trying to dynamically handle missing JSON elements based on an array of expected elements):
foreach ($data as $item) {
foreach ($properties as $property) {
if (empty($item->{$property})) {
// Do something
}
}
}
Each $item in $data should have the properties 'foo' and 'bar'. If empty(), I'll handle them.
I'm trying to get the loop (in line 3) to access $item-{'foo'} and $item-{'bar'}, but it's not working.
Any idea why?
Thanks!