如何使用get_object_vars获取属性的层次结构顺序?

时间:2013-07-03 18:26:58

标签: php arrays class oop step

我有一些相互扩展的类,每次添加更多属性。

现在我需要获取一个类的所有属性的列表,但是在 order 中声明了它们,并且首先使用父类的属性。

例如:

class foo {
    public $a = 1;
    public $c = 2;
    public $d = 3;
}

class foo2 extends foo {
    public $b = 4;
}

$test = new foo2;

var_dump(get_object_vars($test));

这给出了:

array(4) { ["b"]=> int(4) ["a"]=> int(1) ["c"]=> int(2) ["d"]=> int(3) } 

但我想:

array(4) { ["a"]=> int(1) ["c"]=> int(2) ["d"]=> int(3) ["b"]=> int(4) } 

有什么办法可以实现吗?

更新: 的 我需要这个的原因是因为我正在转换使用STEP(EXPRESS ISO 10303-21)格式的文件(并返回!)。 (有关更多信息,请参阅此内容:http://en.wikipedia.org/wiki/ISO_10303-21)此格式是某种序列化对象结构。我在PHP中重新创建了所有对象类,但由于在STEP中属性的顺序至关重要,因此我需要完全相同的属性顺序。

1 个答案:

答案 0 :(得分:2)

  

有什么办法可以实现吗?

目前还不完全清楚你需要什么(以及你的动机是什么,以便提出具体的建议),但你可以通过PHP Reflection来寻找你所需要的。

您可以通过获取所有祖先类直到根类,然后在所有这些类上读取所有属性。请使用ReflectionClass方法查看ReflectionClass::getDefaultProperties()课程。

参见

希望这有帮助,如果您遇到任何问题,请告诉我。

Example:

<?php

class root {
   public $property = 1;
}

class parentClass extends root {
   public $ads = FALSE;
}

class child extends parentClass {
   public $child = TRUE;
}

$class = 'child';

$chain = array_reverse(class_parents($class), true) + [$class => $class];

$props = [];

foreach($chain as $class)
{
     $props += (new ReflectionClass($class))->getDefaultProperties();    
}

print_r($props);

节目输出:

Array
(
    [property] => 1
    [ads] => 
    [child] => 1
)