Constants and enums in PHP

We can define constants in PHP using the define() built-in function:

define('TEST', 'some value');

And then we can use TEST as if it was a variable, but without the $ sign:

define('TEST', 'some value');

echo TEST;

We use uppercase identifiers as a convention for constants.

Interestingly, inside classes we can define constant properties using the const keyword:

class Dog {
  const BREED = 'Siberian Husky';
}

By default they are public but we can mark them as private or protected:

class Dog {
  private const BREED = 'Siberian Husky';
}

Enums allow you to group constants under a common “root”. For example you want to have a Status enum that has 3 states: EATING SLEEPING RUNNING, the 3 states of a dog’s day.

So you have:

enum Status {
  case EATING;
  case SLEEPING;
  case RUNNING;
}

Now we can reference those constants in this way:

class Dog {
  public Status $status;
}

$dog = new Dog();

$dog->status = Status::RUNNING;

if ($dog->status == Status::SLEEPING) {
  //...
}

Enums are objects, they can have methods and lots more features than we can get into here, in this short introduction.

Download my free PHP Handbook!