So, I have a object with structure similar to below, all of which are returned to me as stdClass
objects
$person->contact->phone;
$person->contact->email;
$person->contact->address->line_1;
$person->contact->address->line_2;
$person->dob->day;
$person->dob->month;
$person->dob->year;
$album->name;
$album->image->height;
$album->image->width;
$album->artist->name;
$album->artist->id;
etc... (note these examples are not linked together).
Is it possible to use variable variables to call contact->phone
as a direct property of $person
?
For example:
$property = 'contact->phone';
echo $person->$property;
This will not work as is and throws a E_NOTICE
so I am trying to work out an alternative method to achieve this.
Any ideas?
In response to answers relating to proxy methods:
And I would except this object is from a library and am using it to populate a new object with an array map as follows:
array(
'contactPhone' => 'contact->phone',
'contactEmail' => 'contact->email'
);
and then foreaching through the map to populate the new object. I guess I could envole the mapper instead...
Simplest and cleanest way I know of.
Usage
If i was you I would create a simple method
->property();
that returns$this->contact->phone
Besides making
function getPhone(){return $this->contact->phone;}
you could make a magic method that would look through internal objects for requested field. Do remember that magic methods are somewhat slow though.You could use type casting to change the object to an array.
It's not possible to use expressions as variable variable names.
But you can always cheat:
I think this is a bad thing to to as it leads to unreadable code is is plain wrong on other levels too, but in general if you need to include variables in the object syntax you should wrap it in braces so that it gets parsed first.
For example:
The same applies if you need to access an object that has disalowed characters in the name which can happen with SimpleXML objects regularly.