doureng5668 2013-07-03 18:26
浏览 68
已采纳

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

I have some classes that extend each other, each time adding more properties.

Now I need to get a list of all properties of a class, but in the order that they were declared, with the properties of the parent class first.

For example :

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

This gives :

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

but I want :

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

Is there any way this could be achieved?

UPDATE: The reason I need this, is because I'm converting a file that uses the STEP (EXPRESS ISO 10303-21) format (and back!). (See this for more information : http://en.wikipedia.org/wiki/ISO_10303-21) This format is some kind of serialized objects structure. I recreated all object classes in PHP, but since in STEP the order of the properties is crucial, I need the exact same order of the properties.

  • 写回答

1条回答 默认 最新

  • dr2898 2013-07-03 18:46
    关注

    Is there any way this could be achieved?

    It's not totally clear what exactly you need (and what your motivation is which would have been good to know to give concrete suggestions), but what you're looking for is possible by using PHP Reflection.

    You do so by getting all ancestor classes until the root class, and then you read all properties with it on all these classes. See the ReflectionClass class with it's ReflectionClass::getDefaultProperties() method.

    See as well

    Hope this is helpful, let me know if you run into any problems with that.

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

    Program Output:

    Array
    (
        [property] => 1
        [ads] => 
        [child] => 1
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题