如何迭代当前类属性(不是从父类或抽象类继承)?
我知道 PHP5 将允许您迭代类的属性。但是,如果该类扩展另一个类,那么它也将包含在父类中声明的所有属性。一切都很好,没有什么可抱怨的。
但是,我始终将 SELF 理解为指向当前类的指针,而 $this 也指向当前对象(包括从父级继承的内容)
是否有任何方法可以仅迭代当前类的属性。我问这个的原因......我正在使用 CI 并迭代 $this 包括大量我不需要的父属性。
<?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
I DON'T Want to see "s_parent => Parent sez hi!"
我只想迭代当前类的属性。不是那些在其他地方继承的。
提前致谢。
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.
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)
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()
The output is
s_parent => Parent sez hi!
s_child => Child sez hi!
s_foobar => What What!!
i_lucky_number => 7
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.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用反射方法,您可以执行以下操作:
Using the Reflection methods, you could do the following: