2

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

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

4

1 回答 1

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));
于 2013-07-12T16:19:07.027 回答