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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With