Beeelze
Beeelze

Reputation: 503

PHP retrieve object's getter methods only once in an array of objects

I've got an array of 20 objects that are all the same. These objects are all the same and contain a couple of properties and some getters and setters. I'm converting the property data to an HTML table like so:

public function addBody($objects) {        
    $ret = (string) NULL;

    foreach($objects as $object) {
        $ret .= '<tr>';

        $methods = get_class_methods($object);        
        foreach($methods as $method) {
            if(strpos($method, 'get') !== false) {
                $ret .= '<td>' . call_user_func(array($object, $method)) . '</td>';
            }
        }

        $ret .= '</tr>';
    }

    return $ret;
}

I'm iterating through my array of objects and then I get all methods of each object where I filter on only the getters (with strpos). The function works but retrieving all object methods is a waste of time. A solution I could think of is getting the first object and retrieve all its methods (getters) and use that in my addBody function.

Would this be a good solution of is there a better one?

Upvotes: 2

Views: 3663

Answers (2)

ksno
ksno

Reputation: 487

I'm not sure about your definition of better, but sure there is another one... Less code and one getter to access any property for your specific case.

Our simple entity:

class myEntity {
   private $name;
   private $age;

   public function __get($property) {
      if (property_exists($this, $property)) {
         return $this->$property;
      }
      return null;
   }
}

and then in your method:

public function addBody($entities, $properties) {        
    $ret = '';

    foreach($entities as $entity) {
        $ret .= '<tr>';
        foreach($properties as $property) {
           $ret .= '<td>' . $entity->__get($property) . '</td>';
        }
        $ret .= '</tr>';
    }

    return $ret;
}

where you have a list of entities:

$entities = array ( new myEntity(), new myEntity()); 
$properties = array ('name', 'age');

var_dump($object->addBody($entities, $properties));

Upvotes: 0

Pyton
Pyton

Reputation: 1319

Check this:

public function addBody($objects) {
    $ret = '';
    $obectMethods = get_class_methods(current($objects));
    $methods = array_filter($obectMethods, function($method) {
        return strpos($method, 'get') !== false;
    });

    foreach($objects as $object) {
        $ret .= '<tr>';

        foreach($methods as $method) {
            $ret .= '<td>' . call_user_func(array($object, $method)) . '</td>';
        }

        $ret .= '</tr>';
    }

    return $ret;
}

First we retrieve methods from first object and use them in foreach loop.

Upvotes: 3

Related Questions