Skip to content
Advertisement

How to Dynamically Access Objects in PHP

I have two stdClass Object’s that have a number of fields. I cannot change the object layout or structure.

For example, they both have a phone number:

Object A

[phone] => Array
(
[0] => stdClass Object
(
[value] => '+1 123 456 7890'
[primary] => 1
)
)

Object B

[phone] => '+1 123 456 7890'

I want to dynamically access them with a database entry. In other words, to access ‘phone’ in Object B, it is simply:

$objB->phone

And in the database, I would store the field as ‘phone’, assign this value to a variable e.g. $field and the code would be:

$objB->{"$field"}

The issue arises however if I want to map Object A. To access the phone value, I would need to:

$objA->phone[0]->value

But as I have many fields and many mappings, how do I dynamically set up access to these fields?

Assuming I had a database entry like:

phone.0.value

This could be easily translated to:

$objA->{"$field1"}[$key]->$field2

But what happens in a dynamic or nested case, for example, another field is:

email.company.0.value.0

I’m not aware of a way to access this value dynamically. In other words, how can I build access on the fly for a given database entry?

$objA->{"$field1"}->{"$field2"}[$key1]->$field3[$key2]

Advertisement

Answer

You can create a function for doing this:

function test($str, $c) {
    $res = $c;
    $array = explode('.', $str);
    foreach ($array as $item) {
        if (is_numeric($item)) {
            $res = $res[$item];
        } else {
            $res = $res->$item;
        }
    }
    return $res;
}
// $c is your StdClass
echo test('email.company.0.value.0', $c);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement