Skip to content

Instantly share code, notes, and snippets.

@maximgrynykha
Created January 26, 2022 15:30
Show Gist options
  • Save maximgrynykha/ef788dec482c80331530bdbfcba56f3b to your computer and use it in GitHub Desktop.
Save maximgrynykha/ef788dec482c80331530bdbfcba56f3b to your computer and use it in GitHub Desktop.
Dynamic instantiation of object through constant. [PHP 8.1+]
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