As of PHP 8.2, “dynamic properties” have been deprecated and will be removed in PHP 9.0, see https://php.watch/versions/8.2
Before refactoring dynamic properties into a WeakMap, there are supposed to be a few exemptions from the deprecation (cf. the above link), and one of these exemptions are classes with __get
and __set
magic methods. And indeed, while on PHP 8.2, my code produced no deprecation notice.
However, it seems that after upgrade to PHP 8.3, the deprecation notice is issued in the body of the following, i.e., in the very implementation of those exempting magics:
public function __set($property_name, $value)
{
$this->$property_name = $value;
}
On https://php.watch/versions/8.3 and https://www.php.net/releases/8.3/en.php , I find no hints that the exemption was removed.
Question: Is this a negligience in the PHP 8.3 documentation, or am I missing some reason why “my” __set
(and similar __get
) are not good enough to count for the exemption?
(Meanwhile, I added the #[AllowDynamicProperties]
to the class, but am still curious)
1
This notice is not for the __get
and __set
magic methods, but for accessing a non-existent property. There seems to be an issue with the report on the line number. For example:
class Foo
{
private $a;
public function __set($property_name, $value)
{
$this->$property_name = $value;
}
}
$o = new Foo;
$o->a = 1; # OK, because Foo::$a exists
$o->b = 1; # Deprecated: Creation of dynamic property Foo::$b is deprecated
To avoid this potential problem, you can check if this property exists before assigning a value:
public function __set($property_name, $value)
{
if(property_exists($this, $property_name))
$this->$property_name = $value;
else
# throw exception, log error, save the value to somewhere, etc.
}