PHPexp logo PHPexp

Dynamically check if an enum is defined in PHP

Published on

Sometimes you make a mess, and you somehow end up in a situation where you have to dynamically check if an enum exists. Don't worry about it, it happens to the best of us. To dynamically check if an enum is defined, you can pass the FQN of an enum into the defined() function:

if (defined('App\Support\Enums\UserRole::'.$role)) {
    // true if this enum case exists

If you want to get the value of a PHP enum dynamically, you can use the constant() function:

$enum = constant('App\Support\Enums\UserRole::'.$role);

Level up your Laravel deployments

If you aren't happy with your current deployment strategy for your Laravel apps, check out my premium deployment script.

Deploy with GitHub Actions Deploy with GitLab CI/CD