你如何遍历当前的类属性(不是从父类或抽象类继承的)?

2022-01-24 00:00:00 class iteration properties php

我知道 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}
";
  }
}

相关文章