Checking if a PHP variable is an enumeration

Published on 2022-12-09 • Modified on 2022-12-09

This snippet shows how to check if a variable is an enumeration. No is_enum() function exists because is_*() functions don't apply to objects. We have to do this instance check on the UnitEnum interface instead.



namespace App\Controller\Snippet;

use App\Entity\Article;
use App\Enum\ArticleType;

 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet233Trait
    public function snippet233(): void
        $myEnumCase = ArticleType::BLOG_POST;
        $article = new Article();

        echo '$myEnumCase: '.($myEnumCase instanceof \UnitEnum ? 'it is an enum! ✅' : 'Not an enum ❌'); // @phpstan-ignore-line
        echo PHP_EOL;
        echo '$article: '.($article instanceof \UnitEnum ? 'it is an enum ! ✅' : 'Not an enum ❌'); // @phpstan-ignore-line

        // That's it! 😁

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!