php,如何获取所有私有变量EXCEPT继承的?

时间:2017-07-20 16:48:12

标签: php reflection

Class A
{
    Private $a;
}

Class B extends A
{
    Private $b;

    Public function list()
    {
        Var_dump($this);
    }

(New B())->list()

它会打印来自A的变量。我想仅从B获取变量。怎么做?

1 个答案:

答案 0 :(得分:1)

使用反射可以执行此操作,例如:

Class A
{
    Private $a;
    Protected $e;
}

Class B extends A
{
    Private $b;
    Private $d;

    Protected $c;

    Public function list()
    {
        $ref = new ReflectionClass(__CLASS__);
        $ownProps = array_filter($ref->getProperties(), function($property) {
            return $property->class == __CLASS__ && $property->isPrivate();
        });

        print_r($ownProps);
    }
}

(New B())->list();

输出:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => b
            [class] => B
        )

    [1] => ReflectionProperty Object
        (
            [name] => d
            [class] => B
        )

)