Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Nayjest/9023111 to your computer and use it in GitHub Desktop.
Save Nayjest/9023111 to your computer and use it in GitHub Desktop.
PHP: Instantiate a class by class name and arguments
<?php
function makeInstance($class, $arguments = [])
{
switch (count($arguments)) {
case 0: return new $class();
case 1: return new $class(array_shift($arguments));
case 2: return new $class(array_shift($arguments), array_shift($arguments));
default:
$reflection = new \ReflectionClass($class);
return $reflection->newInstanceArgs($arguments);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment