Try first month for just ₹ 94.00
Get ₹ 94 Offer 🎉

What’s New in PHP 8.2: New Features, Deprecations, and Bug Fixes

PHP 8.2 is just around the corner, scheduled for release on December 8th. It's a release aimed at simplifying the lives of developers by streamlining the coding process and deprecating older functions. Upgrading to the latest PHP version is highly recommended not only for enhanced site security but also for getting accustomed to the new syntax.

Let’s delve into the changes that PHP 8.2 brings to the table so you can make an informed decision about whether to switch to the new version when it becomes available.

New PHP 8.2 Features

In this section, we’ll explore the changes and exciting new features introduced in PHP 8.2.

New Readonly Classes

In PHP 8.1, the readonly class property was introduced, and PHP 8.2 takes it a step further. Now, you can declare an entire class as readonly, making all its properties readonly as well. Note that this doesn't apply to dynamic properties, as declaring them as readonly will result in an error.

Before PHP 8.2:

class ReadOnlyClass {
    public readonly int $number,
    public readonly int $anotherNumber
}

With PHP 8.2:

class ReadOnlyClass {
    public int $number,
    public int $anotherNumber
}

Please keep in mind that you can't declare the following PHP features as readonly: Enums, Traits, and Interfaces.

Allow true, null, and false as Standalone Types

With PHP 8.0, Union Types were introduced, allowing you to declare a type as a union of two or more types. However, using true, null, and false as standalone types was not allowed. PHP 8.2 changes this, enabling you to use these values as standalone types, making the PHP type system more descriptive for declaring return, parameter, and property types.

Redact Sensitive Parameter Value Support

PHP 8.2 introduces a new attribute called SensitiveParameter. It helps conceal sensitive information in stack traces when debugging applications. You can use it like this:

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 simplifies the handling of parameterized MySQLi queries with the mysqli_execute_query($sql, $params) function and the mysqli::execute_query method. These allow you to prepare, bind, and execute queries in a single function call, resulting in a mysqli_result object after successful execution.

Example:

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

PHP 8.2 enables you to declare constants in traits. Until now, traits only allowed code reuse through methods and properties. Here's an 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

PHP 8.2 introduces Disjunctive Normal Form (DNF) types, a standardized way of organizing boolean expressions. It comprises a disjunction of conjunctions or simply boolean OR of ANDs. Examples include:

(A&B)|D
C|(X&D)|null
(A&B&D)|int|null

AllowDynamicProperties Attribute

PHP 8.2 deprecates dynamic variables in classes, resulting in a deprecation message in PHP 8.2 and ErrorException in future versions. To allow dynamic properties for classes, a new #[AllowDynamicProperties] attribute has been added. Here's an example:

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

In this section, we'll explore the features that will be deprecated in PHP 8.2.

utf8_encode() and utf8_decode() Functions

PHP 8.2 will deprecate utf8_encode() and utf8_decode() functions, used for converting between ISO-8859-1 and UTF-8 encoding standards. These functions lacked error messages, and warnings, and had limited encoding support. PHP 9.0 will exclude them entirely, and users are encouraged to use iconv or intl extensions for encoding conversion.

Mbstring: Base64, Uuencode, QPrint, and HTML Entity Encodings

PHP 8.2 will deprecate the mbstring extension's support for Base64, Uuencode, Quoted-Printable, and HTML Entities. These formats processed information in raw bytes instead of sequences of bytes, and PHP already has separate functions for encoding/decoding these formats.

Partially-Supported Callables

PHP 8.2 will deprecate partially-supported callables that don't work with the $callable() pattern. The deprecated callables include various forms like:

$callable = "self::method"
$callable = "parent::method"
$callable = "static::method"
$callable = ["self", "method"]
$callable = ["parent", "method"]
...

To prevent deprecation messages, users can convert all self, parent, and static keywords to their corresponding class names.

${var} String Interpolation

PHP allows variable value replacement within string literals using double quotes. In PHP 8.2, the syntax ${var} and " ${expr}" for variable variables will be deprecated. You can still use the simpler "$myname" and "{$myname}" options without any issues.

Other PHP 8.2 Changes

Random Extension Improvement

PHP 8.2 introduces improvements to the random extension, moving several functions and constants to this extension. These functions will still be available in the global namespace. Notable functions and constants include random_bytes, random_int, rand, getrandmax, srand, lcg_value, mt_rand, mt_getrandmax, mt_srand, MT_RAND_PHP, and MT_RAND_MT19937.

Here’s a list of all the functions and constants that will be moved to the random extension. Keep in mind that they will remain in the global namespace.

MySQLi No Longer Supports libmysql

Starting with PHP 8.2, libmysql support has been removed. PHP historically supported two libraries to connect to MySQL databases: mysqlnd and libmysql. As of PHP 5.4, mysqlnd became the recommended library. With PHP 8.2, libmysql has been removed, and users are required to use the mysqlnd library for connecting to MySQL databases.

Sort Order Changes for the ksort Function

PHP 8.2 introduces a bug fix for the ksort function, making the output of the SORT_REGULAR parameter consistent with other parameters. Prior to PHP 8.2, it prioritized alphabetic keys before numeric keys, but now ksort will place numeric keys before alphabetic keys when sorting.

The str_split Function Returns Empty Arrays for Empty Strings

PHP 8.2 addresses a bug in the str_split function. Previously, when given an empty string, it would return an empty string. In PHP 8.2, it will return an empty array when provided with an empty string.

How to Change the PHP Version

Most hosting providers offer an easy way to switch between PHP versions. If you’re using Sitebuilder.live's control panel, follow these steps:

  1. Log in to your Sitebuilder.live account.
  2. Select your hosting plan.
  3. Search for "PHP Configuration" in the control panel.
  4. You will find a list of the latest stable PHP versions. Select your preferred version and click "Update" to save the changes.

Within this utility, you can also manage PHP extensions and options for each PHP version individually.

Conclusion

PHP 8.2 brings a host of improvements over previous versions, introducing new features like readonly classes, deprecating complex syntax in outdated implementations, and fixing critical bugs to enhance the development workflow. We hope this overview has helped you prepare for the PHP 8.2 release that is already available on Sitebuilder.live!

All prices are listed without GST
© 2022 - 2023 Sitebuilder.live All Rights Reserved
Get ₹ 94 Offer 🎉
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram