如何迭代当前类属性(不是从父类或抽象类继承)? [英] How do you iterate through current class properties (not inherited from a parent or abstract class)?
问题描述
我知道PHP5会让你遍历一个类的属性。但是,如果类扩展了另一个类,那么它将包括在父类中声明的所有属性。
I know that PHP5 will let you iterate through a class's properties. However, if the class extends another class, then it will include all of those properties declared in the parent class as well. That's fine and all, no complaints.
但是,我总是把SELF理解为指向当前类的指针,而$ this也指向当前对象(包括继承的东西从父级)
However, I always understood SELF as a pointer to the current class, while $this also points to the current object (including stuff inherited from a parent)
有没有什么方法,我只能通过当前类的属性进行迭代。为什么我问这个....我使用CI和迭代通过$这包括我不需要的吨的父属性。
Is there any way I can iterate ONLY through the current class's properties. Reason why I'm asking this.... I'm using CI and iterating through $this includes tons of parent properties that I don't need.
<?php
class parent
{
public $s_parent = "Parent sez hi!";
public $i_lucky_number = 6;
}
class child extends parent
{
public $s_child = "Child sez hi!";
public $s_foobar = "What What!!";
public $i_lucky_number = 7;
public iterate()
{
foreach ($this as $s_key => $m_val)
{
echo "$s_key => $m_val<br />\n";
}
}
}
$o_child = new child();
$o_child->iterate()
输出为
s_parent => Parent sez hi!
s_child => Child sez hi!
s_foobar => What What!!
i_lucky_number => 7
我不想看到s_parent => Parent sez hi!
I DON'T Want to see "s_parent => Parent sez hi!"
我只想遍历当前类的属性。
I just want to iterate through the current class's properties. Not those inherited elsewhere.
提前感谢。
推荐答案
您可以执行以下操作:
public function iterate()
{
$refclass = new ReflectionClass($this);
foreach ($refclass->getProperties() as $property)
{
$name = $property->name;
if ($property->class == $refclass->name)
echo "{$property->name} => {$this->$name}\n";
}
}
这篇关于如何迭代当前类属性(不是从父类或抽象类继承)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!