The new features include enums, Fibers, and readonly props.
This week the PHP development group announced the release version 8.1 of the programming language. “PHP 8.1 is a major update of the PHP language,” they claim. “It contains many new features, including enums, readonly properties, first-class callable syntax, fibers, intersection types, performance improvements and more.”
The addition of enumerations is very significant. This is an enumerated type with a fixed number of possible values already available in languages like C and Python. It is declared via the “enum” keyword which should be followed by its name. The syntax is thus quite similar to the one used for classes and interfaces. Options to declare strings or ints (=backed enums), extend classes, and implement interfaces are included and are hoped to help devs write more readable code.
New added features and some deprecations
The language now relaxes the restriction around new expressions inside initializer expressions. PHP 8.1 allows their use in parameter default values, attribute arguments, static variable initializers and global constant initializers. The update also contains “first-class readonly properties”. This alllows developers “to directly expose public readonly properties, without fear that class invariants could be broken through external modification”. Those can be initialised one time only, and only from the scope where it has been declared, otherwise the property will throw an error exception.
Along with the new additions comes a small list of deprecations, which can be found in the PHP wiki. For example, passing null to non-nullable scalar internal arguments or implicitly converting non-integer-compatible float to int will now cause a warning.
PHP 8.1 arrives shortly after the formation of a PHP Foundation was announced. The non-profit is meant to make sure the language continues to be developed by securing funds for language contributors, however “the current RFC process will not change, and language decisions will always be left to the PHP Internals community.”