Enumerations on PHP

In PHP, an enumeration is a value that is set to a fixed set of values. This can be useful when you want to limit the possible values that a variable can take on.

To create an enumeration in PHP, you can use the const keyword. For example:

const DAY_MONDAY = 1;
const DAY_TUESDAY = 2;
const DAY_WEDNESDAY = 3;
const DAY_THURSDAY = 4;
const DAY_FRIDAY = 5;
const DAY_SATURDAY = 6;
const DAY_SUNDAY = 7;

You can then use these constants like any other variable, but you will not be able to assign them a new value.

Watch a course Learn object oriented PHP

For example:

<?php

const DAY_MONDAY = 1;
const DAY_TUESDAY = 2;
const DAY_WEDNESDAY = 3;
const DAY_THURSDAY = 4;
const DAY_FRIDAY = 5;
const DAY_SATURDAY = 6;
const DAY_SUNDAY = 7;

$day = DAY_MONDAY;
echo $day . PHP_EOL; // Outputs 1

$day = DAY_TUESDAY;
echo $day; // Outputs 2

$day = 10; // This would generate an error, as 10 is not a valid enumeration value

You can also create an enumeration by defining a class and using the final keyword to prevent the class from being extended. For example:

<?php

final class Days {
  const MONDAY = 1;
  const TUESDAY = 2;
  const WEDNESDAY = 3;
  const THURSDAY = 4;
  const FRIDAY = 5;
  const SATURDAY = 6;
  const SUNDAY = 7;
}

$day = Days::MONDAY;
echo $day; // Outputs 1

This approach allows you to use the constants in a more intuitive way, as you can access them using the class name and the double colon (::) operator. It also allows you to define additional methods or properties in the class, if needed.