如何迭代当前类属性(不是从父类或抽象类继承)?

发布于 2024-09-27 08:22:11 字数 921 浏览 3 评论 0原文

我知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滿滿的愛 2024-10-04 08:22:11

使用反射方法,您可以执行以下操作:

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";
  }
}

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}\n";
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文