下面的代码使得这一点更容易解释:
<?php
class a
{
public $dog = 'woof';
public $cat = 'miaow';
private $zebra = '??';
}
class b extends a
{
protected $snake = 'hiss';
public $owl = 'hoot';
public $bird = 'tweet';
}
$test = new b();
print_r(get_object_vars($test)); 目前,它返回:
Array
(
[owl] => hoot
[bird] => tweet
[dog] => woof
[cat] => miaow
)如何才能找到仅在类b中定义或设置的属性(例如,仅在owl和bird中定义或设置)?
发布于 2013-07-13 00:19:07
使用ReflectionObject执行以下操作:
$test = new b();
$props = array();
$class = new ReflectionObject($test);
foreach($class->getProperties() as $p) {
if($p->getDeclaringClass()->name === 'b') {
$p->setAccessible(TRUE);
$props[$p->name] = $p->getValue($test);
}
}
print_r($props);输出:
Array
(
[snake] => hiss
[owl] => hoot
[bird] => tweet
)getProperties()将返回该类的所有属性。之后,我将使用$p->getDeclaringClass()检查声明类是否为b
此外,还可以将其概括为一个函数:
function get_declared_object_vars($object) {
$props = array();
$class = new ReflectionObject($object);
foreach($class->getProperties() as $p) {
$p->setAccessible(TRUE);
if($p->getDeclaringClass()->name === get_class($object)) {
$props[$p->name] = $p->getValue($object);
}
}
return $props;
}
print_r(get_declared_object_vars($test));https://stackoverflow.com/questions/17619325
复制相似问题