Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

php - How do you iterate through current class properties (not inherited from a parent or abstract class)?

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

}

$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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...