0

When I need to pass an enumeration in a php function, I do like :

public function my_function (MyEnum $second) {

  switch ($second->get_value()) {
  case MyEnum::foo:
    ....
  }
  ....
}

class MyEnum {
  const foo = 0;
  const bar = 1;

  private $value;

  public function __construct ($value) {
    $this->value = $value;
  }

  public function get_value () { return $this->value; }
}

and call like :

my_function(new MyEnum(MyEnum::foo));

Should I DO change my function as to write my_function(MyEnum::foo); ?

I keep writing this way because IDEs show types when auto-completing a function call and php is throwing an Exception if you use another type anyways. Also It is smoothing the documentation writing process.

So I thought this has a lot of advantages right ?

But maybe writing as the latter has others advantages or disadvantages I'm unaware of. Which could be them ?

vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • What is the point of passing `$first` to `my_function()`? – Mark Baker Feb 13 '15 at 09:55
  • @MarkBaker no points, just to look natural, I edited. – vdegenne Feb 13 '15 at 09:59
  • I don't really get why you use so much code to juste return a constant value, you could juste use: `constant('MyEnum::'. $const);`. It will return the value of the given $const (so you don't need to use a switch) – Snroki Feb 13 '15 at 10:11

1 Answers1

1

When creating a new MyEnum like so

my_function(new MyEnum(MyEnum::foo));

your IDE still won't be able catch the problem arising when you supply a non-existant value into the constructor:

my_function(new MyEnum(12345));

Though the IDE does not care, your code may not be so happy.

You can keep IDE code completion, warnings and have improved safety by implementing your enums as a class hierarchy instead:

abstract class MyEnum
{
    const foo = 1;
    const bar = 2;

    protected $value;

    public function get_value()
    {
        return $this->value;
    }
}

class Foo extends MyEnum { protected $value = MyEnum::foo; }
class Bar extends MyEnum { protected $value = MyEnum::bar; }

function my_function (MyEnum $second)
{
    switch ($second->get_value()) {
        case MyEnum::foo:
            return 'foo';
            break;
        case MyEnum::bar:
            return 'bar';
            break;
        default:
            // This won't happen
            break;
    }
}

echo my_function(new Foo), PHP_EOL;
echo my_function(new Bar), PHP_EOL;

Output:

foo
bar
mhall
  • 3,671
  • 3
  • 23
  • 35
  • Well, at least it is one way to do it. I have seen it around and I use it quite often myself. Enums have been discussed earlier on this site, like [here](http://stackoverflow.com/questions/254514/php-and-enumerations) and all implementations have its pros and cons. – mhall Feb 13 '15 at 12:57