【发布时间】:2010-04-12 06:36:33
【问题描述】:
我有一个类可以扩展另一个类。
当我迭代当前对象时,我会获得所有属性,甚至是超类中的属性。
我只想遍历当前对象。我该怎么做?
foreach($this as $key => $value) {
echo $key . ': ' . $value;
}
【问题讨论】:
我有一个类可以扩展另一个类。
当我迭代当前对象时,我会获得所有属性,甚至是超类中的属性。
我只想遍历当前对象。我该怎么做?
foreach($this as $key => $value) {
echo $key . ': ' . $value;
}
【问题讨论】:
非常有趣的问题。
我强烈建议您阅读此处的示例 - 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+ 中工作,因为它使用了在此之前不可用的反射。您可以在此处阅读有关反射的更多信息 - 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;
}
【讨论】:
您也可以尝试使用 PHP 反射 http://php.net/manual/en/book.reflection.php
我猜你可以使用@Ivo Sabev 回答是:
$properties = get_class_vars(ChildClass);
$bproperties = get_class_vars(ParentClass);
现在遍历所有未出现在 $bproperties 中的 $properties。
【讨论】:
get_class_vars 手册页在用户 cmets 部分(最顶部)中包含了执行此操作的示例。
【讨论】: