Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Access nested object properties via dot notation

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'); 
like image 483
AndrewMcLagan Avatar asked May 29 '26 19:05

AndrewMcLagan


1 Answers

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');
like image 168
ShiraNai7 Avatar answered Jun 01 '26 09:06

ShiraNai7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!