Last active
January 21, 2022 08:48
-
-
Save Nayjest/9023111 to your computer and use it in GitHub Desktop.
PHP: Instantiate a class by class name and arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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