PHP:通过点表示法访问嵌套对象属性

时间:2016-06-28 23:16:46

标签: javascript php oop coding-style standards

通过“dot notion”字符串访问对象的嵌套属性的简单方法是什么?

例如:

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

1 个答案:

答案 0 :(得分:3)

没有简单方法来执行此操作。您必须解析路径字符串,然后逐步达到所需的值。

结帐Symfony PropertyAccess Component。它可以作为独立的库使用,而不需要框架的其余部分。

use Symfony\Component\PropertyAccess\PropertyAccess;

$accessor = PropertyAccess::createPropertyAccessor();

$eyeColour = $accessor->getValue($john, 'eyes[0].colour.hexValue');