PHP 8.2 is on its way, launched at December 8th. The primary focus for this version is making life easier for developers by simplifying the coding process and deprecating some of the older functions. As with any new PHP release, it’s recommended to upgrade to take advantage of the latest security features and get accustomed to the new syntax.
Here’s an overview of all the changes coming in PHP 8.2 so you can decide if it’s worth upgrading when the new version arrives.
Features New PHP 8.2
In this section, we’ll introduce the changes and new features of PHP 8.2.
Read-only Classes
The readonly class property was released in version 8.1, and PHP 8.2 further improves on it. Now, you’ll be able to declare a whole class as readonly. Doing so will change all that class’s properties to readonly. This won’t work for dynamic properties – declaring them as readonly will result in an error.
To declare a class as readonly, you can use the following syntax:
class ReadOnlyClass
{
public readonly int $number,
public readonly int $anotherNumber
}
With PHP 8.2, the process has been thoroughly simplified:
class ReadOnlyClass
{
public int $number,
public int $anotherNumber
}
Note that the following PHP features can’t be declared:
- Enums – they can’t contain properties at all.
- Traits.
- Interfaces.
Allow true, null, and false as Standalone Types
With PHP 8.0, users were presented with support for Union Types. A type declared as a union of two or more types means that it could be any of those types. Even though you could use false and null as possible types, using them as standalone types was not allowed – until now.
As of PHP 8.2, it will be possible to use false and null as standalone types. With this addition, the PHP type system will be more descriptive as you’ll be able to more accurately declare return, parameter, and property types. This is a much-anticipated improvement for the PHP language overall.
Redact Sensitive Parameter Value Support
The Sensitive Parameter attribute will be added in PHP 8.2 and will prevent sensitive information from being displayed or logged when an application encounters an error. This is extra helpful if you want to debug an application and see why it failed. The attribute will look like this in practice:
function passwords(
$publicpassword,
#[\SensitiveParameter] $secretpassword
) {
throw new \Exception('Error');
}
passwords('publicpassword', 'secretpassword');
New mysqli_execute_query Function and mysqli::execute_query Method
PHP 8.2 introduces a new, easier way to handle parameterized MySQLi queries. With the mysqli_execute_query($sql, $params) function and the mysqli::execute_query method, you can prepare, bind, and execute queries all within the same function. After successfully running a query, you’ll be presented with a mysqli_result object.
RFC’s proposed function looks like this:
foreach ($db->execute_query('SELECT * FROM user WHERE name LIKE ? AND type_id IN (?, ?)', [$name, $type1, $type2]) as $row) {
print_r($row);
}
Allow Constants in Traits
With the release of PHP 8.2, you will be able to declare constants in traits. This is a useful addition as it will allow traits to reuse code by defining methods and properties.
Here’s an official RFC proposal example:
trait Foo {
public const FLAG_1 = 1;
protected const FLAG_2 = 2;
private const FLAG_3 = 2;
public function doFoo(int $flags): void {
if ($flags & self::FLAG_1) {
echo 'Got flag 1';
}
if ($flags & self::FLAG_2) {
echo 'Got flag 2';
}
if ($flags & self::FLAG_3) {
echo 'Got flag 3';
}
}
}
New Disjunctive Normal Form (DNF) Types
The new Disjunctive Normal Form (DNF) types feature in PHP 8.2 will help you standardize boolean expressions. In other words, it will help you write expressions using OR of ANDs, which will be easier to understand and work with.
An RFC proposal example can be found below:
// Accepts an object that implements both A and B,
// OR an object that implements D.
(A&B)|D
// Accepts an object that implements C,
// OR a child of X that also implements D,
// OR null.
C|(X&D)|null
// Accepts an object that implements all three of A, B, and D,
// OR an int,
// OR null.
(A&B&D)|int|null
AllowDynamicProperties Attribute
In PHP 8.2, dynamic variables in classes will be deprecated, which means a deprecation message will appear in PHP 8.2 and ErrorException will occur in future versions of PHP.
To allow for dynamic properties in classes, a new
An RFC example looks like this:
class Foo {}
$foo = new Foo;
// Deprecated: Creation of dynamic property Foo::$bar is deprecated
$foo->bar = 1;
// No deprecation warning: Dynamic property already exists.
$foo->bar = 2;
Deprecated Features in PHP 8.2
This section contains a list of all the features that will be deprecated in PHP 8.2.
utf8_encode() and utf8_decode() Functions
The utf8_encode() and utf8_decode() functions will be deprecated as of PHP 8.2 and excluded from PHP 9.0 due to a lack of error messages, warnings, and limited encoding support. As an alternative, users can use the iconv or intl extensions to convert the encoding standard.
Mbstring: Base64, Uuencode, QPrint, and HTML Entity Encodings
The Mbstring extension is used to convert character encoding standards such as UTF-8/16/32 and ISO-8859-1. It also supports Base64, Quoted-Printable, Uuencode, and HTML Entities.
However, these formats process information in raw bytes instead of sequences of bytes. It’s also worth noting that PHP already has separate functions to encode/decode these formats. Thus, PHP 8.2 will deprecate the mbstring extension with the following labeled encodings:
BASE64
UUENCODE
HTML-ENTITIES
html (alias of HTML-ENTITIES)
Quoted-Printable
qprint (alias of Quoted-Printable)
Partially-Supported Callables
$callable = "self::method";
$callable = "parent::method";
$callable = "static::method";
$callable = ["self", "method"];
$callable = ["parent", "method"];
$callable = ["static", "method"];
$callable = ["MyClass", "MyParentClass::myMethod"];
$callable = [new MyClass(), "MyOtherClass::myMethod"];
In order to prevent the deprecation message from appearing, users can convert all self, parent, and static keywords to the corresponding class names.
${var} String Interpolation
PHP allows users to replace variable values within a string literal using double quotes, as in the following examples:
“$myname” – directly embedding variables.
“{$myname}” – braces outside the variable.
“${myname}” – braces after the dollar sign.
” ${expr}” – variable variables equivalent to using (string) ${expr}
While the last two options offer the same functionality, their syntax is quite complex. That’s why they’ll be deprecated in PHP 8.2. You’ll still be able to use the first two options without any issues.
• Other PHP 8.2 Changes
• Random Extension Improvement
From PHP 8.2 onwards, a number of random number generation functions will be moved to a new extension called “random”. This extension will be included by default in PHP, with no option to disable it.
The following functions and constants will be moved to the “random” extension. Note that they will remain in the global namespace:
random_bytes function
random_int function
rand function
getrandmax function
srand function
lcg_value function
mt_rand function
mt_getrandmax function
mt_srand function
MT_RAND_PHP constant
MT_RAND_MT19937 constant
MySQLi No Longer Supports libmysql
The mysqlnd library has been the recommended way to connect MySQL databases with PHP since version 5.4. To simplify code testing in PHP, the decision was made to remove support for the libmysql library with PHP 8.2.
This means that you’ll need to use the mysqlnd library from now on if you want to connect to a MySQL database using PHP.
Sort Order Changes for the ksort Function
The ksort function sorts an array by key in ascending order. In PHP 8.2, a bug fix will be introduced to make the output of the SORT_REGULAR parameter consistent with the other parameters. Up until PHP 8.2, it prioritized alphabetic keys before numeric keys.
Now, ksort will place numeric keys before alphabetic keys when sorting. This means that sorted keys will look like this:
[“1″ => ”, “2” => ”, “a” => ”, , “b” => ”];
Instead of:
[“a” => ”, “b” => ”, “1” => ”, , “2” => ”];
The str_split Function Returns Empty Arrays for Empty Strings
The str_split function has been updated in PHP 8.2 to return an empty array if given an empty string, rather than an empty string. This bug fix is designed to make the function more consistent with other array-returning functions in PHP.
How to Change the PHP Version
Hostpoco’s cmakes it easy to select your hosting plan and change your PHP version with just a few clicks. This utility also allows you to manage PHP extensions and options for each version individually.
Conclusion
PHP 8.2 is shaping up to be a great release! It introduces a number of new features, like readonly classes, and deprecates several outdated implementations with complex syntax. Additionally, it fixes important bugs to streamline the development workflow and make using PHP easier.
We hope this post has helped you prepare for the upcoming PHP 8.2 launch. We can’t wait for the new version released on December 8th!