vdegenne
vdegenne

Reputation: 13298

enumerations in function's parameters

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 ?

Upvotes: 0

Views: 257

Answers (2)

Daka
Daka

Reputation: 31

PHP 8.1 has introduced enums, so now it's possible to create one of those instead of a class with constants.

Your enum would look like this:

enum MyEnum: int
{
    case foo = 0;
    case bar = 1;
}

You could then use it like this:

my_function(MyEnum::foo);

Upvotes: 0

mhall
mhall

Reputation: 3701

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

Upvotes: 1

Related Questions