Created
February 21, 2021 12:00
-
-
Save matason/5cdeeb4a74e26bc6d631c92f56c72980 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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