PHP and Enumerations

后端 未结 30 2126
有刺的猬
有刺的猬 2020-11-22 13:39

I know that PHP doesn\'t have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values whi

30条回答
  •  礼貌的吻别
    2020-11-22 13:58

    class DayOfWeek {
        static $values = array(
            self::MONDAY,
            self::TUESDAY,
            // ...
        );
    
        const MONDAY  = 0;
        const TUESDAY = 1;
        // ...
    }
    
    $today = DayOfWeek::MONDAY;
    
    // If you want to check if a value is valid
    assert( in_array( $today, DayOfWeek::$values ) );
    

    Don't use reflection. It makes it extremely difficult to reason about your code and track down where something is being used, and tends to break static analysis tools (eg what's built into your IDE).

提交回复
热议问题