只获取扩展类变量

时间:2017-06-12 07:30:53

标签: php oop

我有一个班级:

class Person {
   public $id;
   public $firstName;
   public $lastName
}

和另一个扩展它的人:

class Student extends Person {
   public $grade;
}

问题在于,当我在扩展的Students课程中使用get_object_vars()时,我还会收到来自Person的$id$firstName$lastName。 我怎样才能来自学生的$grade

我尝试将变量作为"受保护",但后来我无法使用get_object_vars()

2 个答案:

答案 0 :(得分:2)

好吧,你可能需要一个额外的方法和Reflection类来获得你想要的结果。

这是您的Person课程未触动过:

class Person {
   public $id;
   public $firstName;
   public $lastName;
}

Student课程以及其他props()方法:

class Student extends Person {
   public $grade, $age;

   function props(){
    $class = new ReflectionClass($this);
    $class = $class->getParentClass();
    $props =  $class->getProperties();

    $original = array_map(function($e){
        return $e->name;
    }, $props);

    $original = array_flip($original);

    return array_diff(array_keys(get_class_vars(__CLASS__)), array_keys($original));
   }
}

现在props()方法将包含仅在子类中声明的属性。

var_export( (new Student)->props() ); // array (0 => 'grade', 1 => 'age',)

答案 1 :(得分:0)

使用修改后的ReflectionClass::getProperties

$studentReflectionClass = new ReflectionClass('Student');
$studentProperties = array_filter(
    $studentReflectionClass->getProperties(),
    function ($properties) use ($studentReflectionClass) {
        return $properties->getDeclaringClass()->getName() === $studentReflectionClass->getName();
    }
);

dump($studentProperties);

输出:

array:1 [                    
    0 => ReflectionProperty {#4
        +name: "grade"
        +class: "Student"
        modifiers: "public"
    }
]
相关问题