Danny Valariola Danny Valariola - 1 year ago 81
PHP Question

PHP multi dimension object attributes access from array

I have an object which contain other objects.
I have an array that describes what is the attributes i need to access.
The Array can change in size.

My question is how can i access the sub-object attributes using the array?

Code example:

$student = new Student();
$arr = ['Grades', 'Score'];
foreach.... {}

expected result:


I need to iterate over the $arr and access the $student sub-object

Answer Source

Something like this:

$student = new Student();
$sub_object = $student;  // or use $student itself if you don't need it
$arr = ['Grades', 'Score'];
foreach ($arr as $v) {
    $sub_object = $sub_object->$v;
echo $sub_object;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download