5 ms·
What is the idiomatic way to have data in an enum in PHP, aka sum types? Sum types in languages like Rust or Haskell or OCaml can have data associated with them
by iso8859-1 6y ago
What is the idiomatic way to have data in an enum in PHP, aka sum types? Sum types in languages like Rust or Haskell or OCaml can have data associated with them. You'll get an error before runtime if you assume a field is available when it isn't.
- duckerude 6y agoThat would probably be union types[0] (or plain old dynamic typing) with checks like `is_null($val)` and `$val instanceof Type`. Offline typecheckers (not included with PHP) can analyze the control flow to prove that any invalid types have been ruled out when an operation happens. It's not nearly as principled as proper sum types, but it works alright in practice. PHP's upcoming enums are simple values, more like C's enums than Rust's enums. [0]: https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.union https://www.php.net/manual/en/language.types.declarations.ph...
- Blikkentrekker 6y agoThere is no need for sum types in a dynamically typed language that provides checking the type conditionally. Sum types are, in effect, a small domain of dynamic typing.
- krick 6y agoThis isn't exactly a sum type. Sum type is basically a Union, a proper algebraic data type, and PHP doesn't have algebraic data types (although, even before type hints it was a relatively common practice to "implement" them via PhpDoc... horrible, I know). Enum is basically a bunch of constants, for all practical purposes. There were enums in Java for a long time, long before languages with more-or-less proper type systems became mainstream, and everybody was fine with a rigid mess of type system Java has. So, to have what effectively is enum in PHP, I do just class Status { const STATUS_A = 'STATUS_A'; const STATUS_B = 'STATUS_B'; // and so on { So it looks like a new enum would be basically just a syntactic sugar for that. (And finally a way to make a type hint for $a = Status::STATUS_A.)
- cannabis_sam 6y ago> everybody was fine with a rigid mess of type system Java has. Were we? Java is literally the language that drove me to hate types and prefer python for a few years, until I learned Haskell..