如何在PHP中的扩展类中获取最后的chid公共属性?

时间:2017-07-27 19:01:48

标签: php

<?php 

class S {
    public $a = 'a';
    protected $b = 'b';
    private $c = 'c';

    function get_last_child_public_properties () {
        /* HOW TO */
    }
}

class A extends S
{
    public $d = 'd';
    protected $e = 'e';
    private $f = 'f';
}

class B extends A
{
    public $g = 'public_g';
    protected $h = 'h';
    private $i = 'i';
    public $j = 'public_j';
}

$b = new B();
$props = $b->get_last_child_public_properties();
/**
 * I expect $props to be equals to :
 * Array : ['g' => 'public_g', 'j' => 'public_j']
 */

1 个答案:

答案 0 :(得分:2)

您应该查看PHP中的Relection - 类。

具体来说,getProperties() - 方法返回对象中所有属性的数组作为ReflectionProperty的实例。

$classInfo= new ReflectionClass($b);
foreach($classInfo->getProperties() as $prop) {
    if ($prop->isPublic() && $prop->getDeclaringClass()->name == $classInfo->name) {
        // $prop is public and is declared in class B
        $propName = $prop->name;
        $propValue = $prop->getValue($b); 

        // Since it is public, this will also work:
        $propValue = $b->$propName
        // $prop->getValue($b) will even work on protected or private properties
    }
}