Skip to content

Instantly share code, notes, and snippets.

@stefanofago73
Created May 16, 2022 20:15
Show Gist options
  • Save stefanofago73/ff3a88015cc73e39bee69ea2cb131e71 to your computer and use it in GitHub Desktop.
Save stefanofago73/ff3a88015cc73e39bee69ea2cb131e71 to your computer and use it in GitHub Desktop.
Example of Usage of UnitEnum, Template and Callable to obtain a "generic function"...
<?php declare(strict_types = 1);
/**
* @template T of \UnitEnum
* @param class-string<T> $enumType
* @return callable():T
**/
function randomEnumGenerator(string $enumType):callable
{
/** @var array<T> $cases **/ $cases = [$enumType,"cases"]();
$len = count($cases)-1;
return fn()=> $cases[rand(0,$len)];
};
enum Direction
{
case North;
case South;
case East;
case West;
}
$gen = randomEnumGenerator(Direction::class);
var_export( $gen());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment