PHP: Accessing an object property with a variable.
Posted
by
Peter
on Stack Overflow
See other posts from Stack Overflow
or by Peter
Published on 2011-01-16T23:50:47Z
Indexed on
2011/01/16
23:53 UTC
Read the original article
Hit count: 173
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!
© Stack Overflow or respective owner