简体   繁体   中英

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'); 

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM