2010-04-12 95 views

回答

1

非常有趣的问题。

我强烈建议阅读这里的例子 - http://dsl093-056-122.blt1.dsl.speakeasy.net/edu/oreilly/Oreilly_Web_Programming_bookshelf/webprog/php/ch06_05.htm他们会给你更多关于自省的见解。关于使用这些方法的引用在这里 - http://www.php.net/manual/en/ref.classobj.php


这里是一个测试案例的功能。它只能在PHP 5+中使用,因为它使用了之前没有的Reflection。你可以阅读更多关于这里的反思 - http://www.php.net/manual/en/class.reflectionclass.php

<?php 

echo '<pre>'; 

class A { 
    public $pub_a = 'public a'; 
    private $priv_a = 'private a'; 
} 

class B extends A { 
    public $pub_b = 'public b'; 
    private $priv_b = 'private b'; 
} 

$b = new B(); 

print_r(getChildrenProperties($b)); 

function getChildrenProperties($object) { 
    $reflection = new ReflectionClass(get_class($object)); 
    $properties = array(); 

    foreach ($reflection->getProperties() as $k=>$v) { 
     if ($v->class == get_class($object)) { 
      $properties[] = $v; 
     } 
    } 

    return $properties; 
} 
+0

有点破解,但代码工作。感谢您挖掘它! – 2010-04-12 07:28:56

1

您也可以尝试使用PHP反射http://php.net/manual/en/book.reflection.php

我想你可以使用@Ivo Sabev答案是做什么:

$properties = get_class_vars(ChildClass); 
$bproperties = get_class_vars(ParentClass); 

而且现在迭代未出现在$ bproperties中的所有$属性。

+0

是的,这是想法,但这些功能实际上不给你私有财产。我没有看ReflectionClass,可能会写一个小函数来完成这个技巧。 – 2010-04-12 06:57:31