如何获取a';最后一代';php中的对象?

如何获取a';最后一代';php中的对象?,php,oop,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 =

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

<?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));    

如何查找仅在类b中定义或设置的属性(例如仅owl和bird)?

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

谢谢,事实证明我最终不需要这么做,但这仍然是一个非常有用的概念:)
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));