Friday, May 25, 2012

PHP and Enums


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 which IDEs' auto completion features could understand.



Constants do the trick, but there's the namespace collision problem and (or actually because ) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely (never?) know how to autofill their keys.



Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enums?


Source: Tips4all

5 comments:

  1. I use something like the following:

    class DaysOfWeek
    {
    const Sunday = 0;
    const Monday = 1;
    // etc.
    }

    var $today = DaysOfWeek::Sunday;

    ReplyDelete
  2. There is a native extension, too.

    http://www.php.net/manual/class.splenum.php

    ReplyDelete
  3. What about class constants?

    <?php

    class YourClass
    {
    const SOME_CONSTANT = 1;

    public function echoConstant()
    {
    echo self::SOME_CONSTANT;
    }
    }

    echo YourClass::SOME_CONSTANT;

    $c = new YourClass;
    $c->echoConstant();

    ReplyDelete
  4. I used classes with constants:

    class Enum {
    const NAME = 'aaaa';
    const SOME_VALUE = 'bbbb';
    }

    print Enum::NAME;

    ReplyDelete
  5. Well, for a simple java like enum in php, I use:

    class SomeTypeName {
    private static $enum = array(1 => "Read", 2 => "Write");

    public function toOrdinal($name) {
    return array_search($name, self::$enum);
    }

    public function toString($ordinal) {
    return self::$enum[$ordinal];
    }
    }


    And to call it:
    SomeTypeName::toOrdinal("Read");
    SomeTypeName::toString(1);

    But I'm a PHP beginner, struggling with the syntax so this might not be the best way. I experimented some with Class Constants, using Reflection to get the constant name from it's value, might be neater.

    ReplyDelete