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 并迭代 $this 包括大量我不需要的父属性.
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 />
";
}
}
}
$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.
提前致谢.
推荐答案
使用反射方法,您可以执行以下操作:
Using the Reflection methods, you could do the following:
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}
";
}
}
这篇关于你如何遍历当前的类属性(不是从父类或抽象类继承的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何遍历当前的类属性(不是从父类或抽象类继承的)?
基础教程推荐
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01