Skip to content

Instantly share code, notes, and snippets.

@zebba
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zebba/7661427cd3b39876449d to your computer and use it in GitHub Desktop.
Save zebba/7661427cd3b39876449d to your computer and use it in GitHub Desktop.
Flexible and secure fromArray implementation
<?php
// ...
class Foo
{
// ...
static public function fromArray(array $data)
{
$o = new self();
$reflection = new \ReflectionClass($o);
$properties = $reflection->getProperties();
$properties = array_map(function ($v) { /* @var $v \ReflectionProperty */
return $v->getName();
}, $properties);
if (array_key_exists('id', $properties)) { unset($properties['id']); }
foreach ($properties as $k) {
$setter = sprintf('set%s', $k);
if (array_key_exists($k, $data) && method_exists($o, $setter)) {
$o->{$setter}($data[$k]);
}
}
return $o;
}
// ...
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment