Skip to content

Instantly share code, notes, and snippets.

@matason
Created February 21, 2021 12:00
Show Gist options
  • Save matason/5cdeeb4a74e26bc6d631c92f56c72980 to your computer and use it in GitHub Desktop.
Save matason/5cdeeb4a74e26bc6d631c92f56c72980 to your computer and use it in GitHub Desktop.
<?php
/**
* Example enum usage.
*
* PHP8.1 will introduce the enum keyword, it will negate the need for the of
* validation code we often see below as enum will "make invalid states
* unrepresentable"
*
* @see https://wiki.php.net/rfc/enumerations
*/
// Old code < PHP8.1
$isValidStatus = function ($status) {
$allowed = ['draft', 'published', 'archived'];
if (in_array($status, $allowed)) {
return true;
}
return false;
};
var_dump($isValidStatus('deleted'));
// New code => PHP8.1
enum Status {
case draft;
case published;
case archived;
}
function setStatus(Status $status)
{
return $status->name;
}
var_dump(setStatus(Status::draft));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment