Skip to content

Instantly share code, notes, and snippets.

@k-holy
Last active December 29, 2015 01:49
Show Gist options
  • Save k-holy/7595487 to your computer and use it in GitHub Desktop.
Save k-holy/7595487 to your computer and use it in GitHub Desktop.
ReflectionClassを使ったファクトリ
<?php
function factory($class, array $options = array())
{
if (count($options) === 0) {
return new $class();
}
$refClass = new \ReflectionClass($class);
$constructor = $refClass->getConstructor();
$arguments = array();
if ($constructor instanceof \ReflectionMethod) {
foreach ($constructor->getParameters() as $param) {
$paramName = $param->getName();
if (array_key_exists($paramName, $options)) {
$arguments[] = $options[$paramName];
unset($options[$paramName]);
} else {
$arguments[] = $param->getDefaultValue();
}
}
}
if (count($options) !== 0) {
throw new \InvalidArgumentException(
sprintf('Not supported parameter [%s]', implode(',', array_keys($options)))
);
}
return (count($arguments) >= 1)
? $refClass->newInstanceArgs($arguments)
: $refClass->newInstance();
}
@k-holy
Copy link
Author

k-holy commented Dec 3, 2013

$options引数のtypo発見をunset()で実装した。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment