Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving only properties of the child class [duplicate]

I have a class like

class parent{
   public $foo;
}

class child extends parent{
   public $lol;

    public function getFields()
    {
        return array_keys(get_class_vars(__CLASS__));
    }
}

and I get a array with the child properties in it to...

array('foo','lol'); 

is there a simple solution to get only the properties from the child class?

like image 289
Sangoku Avatar asked Jun 20 '13 13:06

Sangoku


2 Answers

as posted in the link to How do you iterate through current class properties (not inherited from a parent or abstract class)?

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

It is GREAT solution up voted and favorited! thy!!! who ever linked to this one!

like image 80
Sangoku Avatar answered Nov 23 '22 02:11

Sangoku


Try this approach (may contain pseudo PHP code :))

class parent{
   public $foo;

   public function getParentFields(){
        return array_keys(get_class_vars(__CLASS__));
   }
}

class child extends parent{
   public $lol;

    public function getFields()
    {   
        $parentFields = parent::getParentFields();
        $myfields = array_keys(get_class_vars(__CLASS__));

        // just subtract parentFields from MyFields and you get the properties only exists on child

        return the diff
    }
}

The idea that using parent::getParentFields() function to determine which fields was parent fields.

like image 33
Kemal Dağ Avatar answered Nov 23 '22 03:11

Kemal Dağ