Dynamic Properties in PHP 8.2

Dani 0 Tallied Votes 13 Views Share

In my increasingly futile attempt to remain using the now-defunct CodeIgniter 3 framework, I came across something that I figure might be worth sharing in case anyone else is maintaining older PHP codebases and suddenly things start breaking after a PHP upgrade.

With PHP 8.2, there’s a new warning that’s catching a lot of people off guard: dynamic properties are now deprecated. What that means is, you can no longer just assign a new property to an object without explicitly declaring it first in the class. If you do, PHP throws a warning like:

Creation of dynamic property SomeClass::$foo is deprecated

This happens when you do things like:

$user = new User();
$user->nickname = 'Dani';

If nickname wasn’t already declared in the User class, PHP used to just shrug and let it slide. Not anymore.

Obviously the best thing to do if you encounter this is declare properties ahead of time (obviously). However, if you prefer not to touch and sort through and refactor a lot of old, crusty code that was not written by you, there's an easy fix: Add #[\AllowDynamicProperties] to the top of the class, as so:

#[\AllowDynamicProperties]
class Images extends CI_Controller
{
    ...
}

It's a nice and easy MacGyver patch, until it stops working as well. (DaniWeb is currently on PHP 8.3.8 and it's still working.)

Hope this helps someone!

Dani 4,653 The Queen of DaniWeb Administrator Featured Poster Premium Member

Oh, and an important bit I forgot to mention: PHP's built-in stdClass has the #[AllowDynamicProperties] attribute already added. In fact, you can see in the PHP docs that the definition of the stdClass is "a generic empty class with dynamic properties." That means that you can always be safe doing things like:

$user = new stdClass();
$user->nickname = 'Dani';
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.