cezarlamann
cezarlamann

Reputation: 1523

How to get an array of property names from base class in an inheritance context with PHP?

Here I have a bunch of entity classes composed like this:

<?php
class BaseModel {
    protected $Id;
    protected $CreateDate;
    protected $LastUpdateDate;
    // public setters, getters and validation methods
    public function getClassFields(){
        // how to get an array containing all property names,
        // including those from inherited classes?
        $array = (array) $this; //this do not work =(
        return $array;
    }
}

class FooModel extends BaseModel {
    protected $Bar;
    protected $Baz;
    protected $Loo;
    // public setters, getters and validation methods
}
?>

I want to get an array containing ["Id", "CreateDate", "LastUpdateDate", "Bar", "Baz", "Loo"]. How do I accomplish this?

What I've tried:

When I try to do an array cast $array = (array) new FooModel() from outside of the class or $array = (array) $this from inside of base class, both do not work... I think that get_object_vars function don't work since all properties are protected.

Should I use reflection instead?

Thank you in advance!

Upvotes: 1

Views: 74

Answers (2)

FirstOne
FirstOne

Reputation: 6217

Since you are trying to get the variables from within the class, you could use a built-in function: get_class_vars.


So here is something more elaborate...

Replace your code with this:

class BaseModel {
    protected $Id;
    protected $CreateDate;
    protected $LastUpdateDate;
    // public setters, getters and validation methods
    public function getClassFields(){
        return array_keys(get_class_vars(get_class($this))); // changed
    }
}

class FooModel extends BaseModel {
    protected $Bar;
    protected $Baz;
    protected $Loo;
    // public setters, getters and validation methods
}

And then, if you use:

$foo = new BaseModel();
print_r($foo->getClassFields());

The output is:

Array ( [0] => Id [1] => CreateDate [2] => LastUpdateDate )

If you use it on the child:

$bar = new FooModel();
print_r($bar->getClassFields());

The output is now:

Array ( [0] => Bar [1] => Baz [2] => Loo [3] => Id [4] => CreateDate [5] => LastUpdateDate )

References:

get_class: Returns the name of the class of an object
get_class_vars: Get the default properties of the class
array_keys: Return all the keys or a subset of the keys of an array


Sidenote: if you don't want your BaseModel class to be instantiated, change it to abstract:

abstract class BaseModel {

Upvotes: 1

Andreas
Andreas

Reputation: 5335

Here is one way to do it.

$ref = new ReflectionClass('FooModel');
$properties = $ref->getProperties();
$result = array();
foreach($properties as $i=>$prop){ 
  $result[] = $prop->getName();
}

The $result array will hold the properties you want.

Upvotes: 2

Related Questions