如何在php中获取“最后一个后代”对象的所有公共属性值?

时间:2013-07-12 16:13:47

标签: php oop

下面的代码使这更容易解释:

<?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类中定义或设置的属性(例如猫头鹰和小鸟)?

1 个答案:

答案 0 :(得分:1)

使用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));