Skip to content

Instantly share code, notes, and snippets.

@estahn
Created February 21, 2013 05:13
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 estahn/5002290 to your computer and use it in GitHub Desktop.
Save estahn/5002290 to your computer and use it in GitHub Desktop.
Our current framework is heavily using a "Factory" to instantiate classes on the fly. It used ReflectionClass::newInstanceArgs() for classes with arguments. Since Reflection is quite slow it decreased our performance. The gist shows a solution that is less beautiful but more performant.
<?php
class Factory
{
// ...
/**
* Helper to instantiate objects with dynamic constructors.
*
* The beautiful way:
* <code>
* $reflection = new ReflectionClass($classNameNormalized);
* return $reflection->newInstanceArgs($arguments);
* </code>
*
* Reflection->newInstanceArgs() is very slow and therefore replaced
* by generated PHP code which is executed with eval.
*
* @param string $class
* @param array $arguments
* @return mixed
*/
public static function createInstance($class, $arguments = null)
{
if (is_null($arguments)) {
return new $class;
}
$instance = null;
$codeScaffold = '$instance = new %s(%s);';
$codeArguments = array();
foreach ($arguments as $index => $argument) {
${'arg' . $index} = $argument;
$codeArguments[] = '$arg' . $index;
}
eval(sprintf($codeScaffold, $class, implode(', ', $codeArguments)));
return $instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment