3

What is a simple method to access nested properties of an object via a "dot notion" string?

For example:

#..........................Classes..........................

class Colour            |   class Eye       |   class Person
{                       |   {               |   {
    $hexValue = #36ff00 |       $colour;    |       $eyes;
}                       |   }               |   }

#..........................Example..........................

$john = new Person;

$eyes = [new Eye, new Eye];

$eyes[0]->color = new Colour;

$eyes[1]->color = new Colour;

$john->eyes = [new Eye, new Eye];

#..........................Question..........................

# How can we do something like this?

$eyeColour = Helper::dot($john, 'eyes[0].colour.hexValue'); 
AndrewMcLagan
  • 13,459
  • 23
  • 91
  • 158
  • Same direction: http://stackoverflow.com/q/38087608/3933332 just got asked 15 minutes ago. Also see the comments to get some ideas. – Rizier123 Jun 28 '16 at 23:17
  • That is for array access, there are a plethora of examples and packages dealing with array dot access. Although none for objects / class instances. – AndrewMcLagan Jun 28 '16 at 23:18

1 Answers1

7

There is no simple method to do this. You'll have to parse the path string and then reach the desired value step by step.

Checkout the Symfony PropertyAccess Component. It can be used as a standalone library without the rest of the framework.

use Symfony\Component\PropertyAccess\PropertyAccess;

$accessor = PropertyAccess::createPropertyAccessor();

$eyeColour = $accessor->getValue($john, 'eyes[0].colour.hexValue');
Shira
  • 6,392
  • 2
  • 25
  • 27