Class A
{
Private $a;
}
Class B extends A
{
Private $b;
Public function list()
{
Var_dump($this);
}
(New B())->list()
它会打印来自A
的变量。我想仅从B
获取变量。怎么做?
答案 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
)
)