And*_*gan 2 javascript php oop standards coding-style
通过“点概念”字符串访问对象的嵌套属性的简单方法是什么?
例如:
#..........................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');
Run Code Online (Sandbox Code Playgroud)
没有简单的方法可以做到这一点。您必须解析路径字符串,然后逐步达到所需的值。
查看Symfony PropertyAccess 组件。它可以用作独立库,无需框架的其余部分。
use Symfony\Component\PropertyAccess\PropertyAccess;
$accessor = PropertyAccess::createPropertyAccessor();
$eyeColour = $accessor->getValue($john, 'eyes[0].colour.hexValue');
Run Code Online (Sandbox Code Playgroud)