Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

What’s new in PHP 8.2

Home  »  Top Tutorials   »   What’s new in PHP 8.2
Posted on September 25, 2022September 25, 2022
568

PHP 8.2 will be released on November 24, 2022. In this post, we’ll go through all features, performance improvements, changes, and deprecations one by one.

Readonly classes rfc

This RFC builds on top of them and adds syntactic sugar to make all class properties readonly at once. Instead of writing this:

class Post
{
    public function __construct(
        public readonly string $title, 
        public readonly Author $author,
        public readonly string $body,
        public readonly DateTime $publishedAt,
    ) {}
}

You can now write this:

readonly class Post
{
    public function __construct(
        public string $title, 
        public Author $author,
        public string $body,
        public DateTime $publishedAt,
    ) {}
}

Functionally, making a class readonly is entirely the same as making every property read-only; but it will also prevent dynamic properties from being added to a class:

$post = new Post(/* … */);

$post->unknown = 'wrong';

Uncaught Error: Cannot create dynamic property Post::$unknown

Note that you can only extend from read-only classes if the child class is read-only as well.

PHP has changed quite a lot, and readonly classes are a welcome addition. You can take a look at my video about PHP’s evolution if you want to as well:

Deprecate dynamic properties rfc

I’d say this is a change for the better, but it will hurt a little bit. Dynamic properties are deprecated in PHP 8.2 and will throw an ErrorException in PHP 9.0:

class Post
{
    public string $title;
}

// …

$post->name = 'Name';

Keep in mind that classes implementing __get and __set will still work as intended:

class Post
{
    private array $properties = [];
    
    public function __set(string $name, mixed $value): void
    {
        $this->properties[$name] = $value;
    }
}

// …

$post->name = 'Name';

If you want to learn more about why deprecations are useful and how to deal with them, you can read this follow-up post on how to deal with deprecations, or you can check out my vlog:

null, true, and false as standalone types rfc

PHP 8.2 adds three new types — or something that looks like it. Common examples are PHP’s built-in functions, which false is used as the return type for when an error occurs. For example in file_get_contents:

file_get_contents(/* … */): string|false

Before PHP 8.2, you could already use false together with other types as a union; but now it can be used as a standalone type as well:

function alwaysFalse(): false
{
    return false;
}

The same now also go for true and null.


Disjunctive Normal Form Types rfc

when combining union and intersection types, intersection types must be grouped with brackets. In practice, that looks like this:

function generateSlug((HasTitle&HasId)|null $post) 
{
    if ($post === null) {
        return '';
    }

    return 
        strtolower($post->getTitle()) 
        . $post->getId();
}

In this case, (HasTitle&HasId)|null is the DNF type.

It’s a nice addition, especially since it means that we can now have nullable intersection types, which is probably the most important use case for this feature.


Constants in traits rfc

You can now use constants in traits:

trait Foo 
{
    public const CONSTANT = 1;
 
    public function bar(): int 
    {
        return self::CONSTANT;
    }
}

You won’t be able to access the constant via the trait’s name, either from outside the trait or from inside it.

trait Foo 
{
    public const CONSTANT = 1;
 
    public function bar(): int 
    {
        return Foo::CONSTANT;
    }
}

Foo::CONSTANT;

You can however access the constant via the class that uses the trait, given that it’s public:

class MyClass
{
    use Foo;
}

MyClass::CONSTANT; // 1

Redact parameters in backtraces rfc

A common practice in any codebase is to send production errors to a service that keeps track of them and will notify developers when something goes wrong. This practice often involves sending stack traces over the wire to a third-party service. There are cases however where those stack traces can include sensitive information such as environment variables, passwords, or usernames.

PHP 8.2 allows you to mark such “sensitive parameters” with an attribute so that you don’t need to worry about them being listed in your stack traces when something goes wrong. Here’s an example from the RFC:

function login(
    string $user,
    #[\SensitiveParameter] string $password
) {
    // …
    
    throw new Exception('Error');
}
 
login('root', 'root');
 
Fatal error: Uncaught Exception: Error in login.php:8
Stack trace:
#0 login.php(11): login('root', Object(SensitiveParameterValue))
#1 {main}
  thrown in login.php on line 8

Fetch properties of enums in const expressions rfc

From the RFC:

This RFC proposes to allow the use of ->/?-> to fetch properties of enums in constant expressions. The primary motivation for this change is to allow fetching the name and value properties in places where enum objects aren’t allowed, like array keys

That means that the following code is now valid:

enum A: string 
{
    case B = 'B';
    
    const C = [self::B->value => self::B];
}

Return type changes for DateTime::createFromImmutable() and DateTimeImmutable::createFromMutable()

Previously, these methods looked like this:

DateTime::createFromImmutable(): DateTime
DateTimeImmutable::createFromMutable(): DateTimeImmutable

In PHP 8.2 those method signatures are changed like so:

DateTime::createFromImmutable(): static
DateTimeImmutable::createFromMutable(): static

This change makes a lot more sense, as it improves static insight possibilities for classes extending from DateTime and DateTimeImmutable. However, technically, this is a breaking change that might affect custom implementations that extend from either of those two classes.


utf8_encode() and utf8_decode() deprecations rfc

In PHP 8.2, using either utf8_encode() or utf8_decode() will trigger these deprecation notices:

Deprecated: Function utf8_encode() is deprecated
Deprecated: Function utf8_decode() is deprecated

The RFC argues that these functions have an inaccurate name that often causes confusion: these functions only convert between ISO-8859-1 and UTF-8, while the function name suggests a broader use. There’s a more detailed explanation of the reasoning in the RFC.

The alternative? The RFC suggests using mb_convert_encoding() instead.


Locale-insensitive strtolower() and strtoupper() rfc

Both strtolower() and strtoupper() are no longer locale-sensitive. You can use mb_strtolower() if you want localized case conversion.


Signature changes to several SPL methods

Several methods of SPL classes have been changed to properly enforce their correct type signature:

SplFileInfo::_bad_state_ex()
SplFileObject::getCsvControl()
SplFileObject::fflush()
SplFileObject::ftell()
SplFileObject::fgetc()
SplFileObject::fpassthru()
SplFileObject::hasChildren()
SplFileObject::getChildren()

New n the modifier in PCRE

You can now use the n modifier (NO_AUTO_CAPTURE) in pcre* functions.


New Random extension rfc

There’s a new random extension added in PHP 8.2, providing a completely new API with improvements across the board.


ODBC username and password escaping

From the UPGRADING guide:

The ODBC extension now escapes the username and password for the case when both a connection string and username/password are passed, and the string must be appended to.

The same applies to PDO_ODBC.

Top Tutorials

Post navigation

Previous Post: PHP 8: Constructor property promotion
Next Post: Dealing with deprecations

Related Posts

  • How to Convert PHP CSV to JSON
  • TOP 10 MOST POPULAR PROGRAMMING LANGUAGES IN 2022
  • How to Delete Files in Ubuntu Command Line
  • PHP 8: Attributes
  • How to Deploy a React application on a cPanel
  • What is SSH in Linux?

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

How to remove index.php from URL in CodeIgniter 4
Destructuring Assignment in ES6- Arrays
HTML Basic Examples
How to change background Opacity when the bootstrap modal is open with CSS?
How to Symfony Request

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved