Created
January 26, 2022 15:30
-
-
Save maximgrynykha/ef788dec482c80331530bdbfcba56f3b to your computer and use it in GitHub Desktop.
Dynamic instantiation of object through constant. [PHP 8.1+]
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
final class InstantiationFailure extends \LogicException implements Exception | |
{ | |
final public const NAMESPACE = __NAMESPACE__; | |
} | |
final class Instance | |
{ | |
/** | |
* Create an instance of a subtype of a certain supertype. | |
* | |
* @param string $subtype | |
* @param string $supertype | |
* | |
* @return object | |
*/ | |
final public static function create(string $subtype, string $supertype): object | |
{ | |
class_alias( | |
InstantiationFailure::class, | |
$exception = basename($supertype).basename(InstantiationFailure::class) | |
); | |
$accessor = $supertype.'::'.mb_strtoupper($subtype); | |
$instance = constant($accessor) | |
?: throw new (InstantiationFailure::NAMESPACE.$exception)($accessor); | |
return new $instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment