Danny Valariola Danny Valariola - 5 months ago 9
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:


$student->$arr[0]->$arr[1];


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

Answer

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;